-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.ts
40 lines (32 loc) · 1.16 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export const makeArray = <T>(val: T | T[]) => (Array.isArray(val) ? val : [val])
export function makeEncryptor(key: string) {
const textToChars = (text: string) =>
text.split('').map((c) => c.charCodeAt(0))
const byteHex = (n: number) => ('0' + Number(n).toString(16)).substring(-2)
const applyKeyToChar = (code: number) =>
textToChars(key).reduce((a, b) => a ^ b, code)
function decrypt(encoded: string) {
return (encoded.match(/.{1,2}/g) || [])
.map((hex) => parseInt(hex, 16))
.map(applyKeyToChar)
.map((charCode) => String.fromCharCode(charCode))
.join('')
}
function encrypt(text: string) {
return textToChars(text).map(applyKeyToChar).map(byteHex).join('')
}
return { encrypt, decrypt }
}
export function lazyJSONParse(json: string): any {
try {
return JSON.parse(json)
} catch {
return {}
}
}
export function delay(time: number) {
return new Promise<void>((resolve) => void setTimeout(() => resolve(), time))
}
export const pathsAreEqual = (actual: string, expected?: string) =>
expected === '*' ? true : actual === (expected || '/')
export const paramsEncoder = makeEncryptor('nothing-secret')