utils
code:script.js
export const sleep = (seconds) =>
new Promise((resolve) => setTimeout(resolve, seconds * 1000, seconds))
export const fetchText = async (url) => {
const res = await fetch(url)
const data = res.text()
return data
}
export const fetchJson = async (url) => {
const res = await fetch(url)
const data = res.json()
return data
}
const getSearchURL = (projectName, query) => {
// TODO: sort: 'update' | 'rank' , limit: number などを設定できるようにする?
return https://scrapbox.io/api/pages/${projectName}/search/query?q=${query}
}
export const fetchScrapboxSearch = async (project, query) => {
const url = getSearchURL(project, query)
return fetchJson(url)
}
export const fetchProjectFaviconUrl = async (projectName) => {
const url = https://scrapbox.io/api/projects/${projectName}
const data = await fetchJson(url)
return data.image
}
export const escapeHTML = (string) => {
if (typeof string !== 'string') {
return string
}
return string.replace(/&'`"<>/g, function (match) { return {
'&': '&',
"'": ''',
'`': '`',
'"': '"',
'<': '<',
'>': '>',
})
}
export const unlink = (text) => {
return text
.split(/\n/)
.map((line) =>
line.replaceAll(
'$<string>'
)
)
.join('\n')
}
export const isASCII = (str) => {
str = str == null ? '' : str
return true
} else {
return false
}
}
export const concatUnit = (singular, plural) => {
return (num) => {
return num === 1 ? ${num} ${singular} : ${num} ${plural}
}
}
export const getRandomInt = (min, max) => {
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min) + min)
}