shadowfacts.net/lib/util.ts

44 lines
1.1 KiB
TypeScript

import { promises as fs } from "fs";
import path from "path";
import hljs from "highlight.js";
export async function write(filePath: string, data: any) {
const dest = path.join("out", filePath);
await fs.mkdir(path.dirname(dest), {
recursive: true
});
await fs.writeFile(dest, data);
}
export function highlight(source: string, language?: string): string {
const res = language ? hljs.highlight(language, source) : hljs.highlightAuto(source);
const highlighted = res.value;
return `<pre class="hljs"><code>${highlighted}</code></pre>`;
}
interface Chunk<T> {
chunk: T[];
index: number;
}
export function chunk<T>(array: T[], size: number): Chunk<T>[] {
const chunks: Chunk<T>[] = [];
for (let i = 0; i < array.length; i += size) {
chunks.push({
chunk: array.slice(i, i + size),
index: i / size
});
}
return chunks;
}
export function fancyLink(text: string, href: string, meta?: string): string {
return `
<a href="${href}" class="fancy-link" ${meta || ""}>
<span aria-hidden="true">{</span>
${text}
<span aria-hidden="true">}</span>
</a>`;
}