-
Notifications
You must be signed in to change notification settings - Fork 546
/
Copy pathutils.ts
51 lines (39 loc) · 1.42 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
41
42
43
44
45
46
47
48
49
50
51
import Prism from 'prismjs';
export type AnyFunction = (...args: never[]) => unknown;
export function debounce<T extends AnyFunction>(fn: T, ms: number): T {
let timer: ReturnType<typeof setTimeout> | undefined;
const handler = (...args: never[]) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
return handler as T;
}
export function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
export function ensureArray<T>(target: T | T[]): T[] {
if (Array.isArray(target)) return target;
return target === undefined ? [] : [target];
}
export function createQueryURL(
raw: Record<string, string | number | undefined>
) {
const params: Record<string, string> = {};
Object.entries(raw).forEach(([key, value]) => {
if (value === undefined) return;
params[key] = typeof value === 'number' ? value.toString() : value;
});
return `?${new URLSearchParams(params)}`;
}
export function highlight(code: string, lang: string) {
const grammar = Prism.languages[lang] ?? Prism.languages.plain;
return Prism.highlight(code, grammar, lang);
}
export async function loadThemeStyles(id: string, theme: string) {
const existed = document.getElementById(id);
if (existed) existed.remove();
const style = document.createElement('style');
style.setAttribute('id', id);
style.textContent = theme;
document.head.appendChild(style);
}