nose-pluto/src/shared/utils.ts

66 lines
1.7 KiB
TypeScript

// How many times does `char` appear in `str`?
export function countChar(str: string, char: string): number {
return str.split(char).length - 1
}
// Generate a 6 character random ID
export function randomId(): string {
return Math.random().toString(36).slice(7)
}
// rng(1, 5) #=> result can be 1 2 3 4 or 5
// rng(2) #=> result can be 1 or 2
export function rng(min: number, max = 0) {
if (min === 0 && max === 0) return 0
if (max === 0) {
max = min
min = 1
}
min = Math.ceil(min)
max = Math.floor(max)
return Math.floor(Math.random() * (max - min + 1)) + min
}
// randomElement([5, 7, 9]) #=> 7
export function randomElement<T>(list: T[]): T | undefined {
if (!list.length) return
return list[rng(0, list.length - 1)]
}
// randomIndex([5, 7, 9]) #=> 1
export function randomIndex<T>(list: T[]): number | undefined {
if (!list.length) return
return rng(0, list.length - 1)
}
// unique([1,1,2,2,3,3]) #=> [1,2,3]
export function unique<T>(array: T[]): T[] {
return [...new Set(array)]
}
// import a typescript module. caches in production, doesn't in dev.
export async function importUrl(url: string) {
url += url.includes("?") ? "&" : "?"
url += "t=" + (nodeEnv() === "production" ? gitSHA() : Date.now())
console.log("-> import", url)
return import(url)
}
// "production" or nuttin
function nodeEnv(): string | undefined {
if (typeof process !== 'undefined' && process.env?.NODE_ENV)
return process.env.NODE_ENV
if (typeof globalThis !== 'undefined' && (globalThis as any).NODE_ENV)
return (globalThis as any).NODE_ENV
return undefined
}
// should always be set
function gitSHA(): string {
return (globalThis as any).GIT_SHA
}