jillo-bot/src/lib/util.ts

44 lines
1.1 KiB
TypeScript

import * as fsp from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { randomBytes } from 'crypto';
export async function exists(file: string) {
try {
await fsp.stat(file);
return true;
} catch(_err) {
return false;
}
}
export function getSign(n: number) {
if (n > 0) return '+';
if (n < 0) return '-';
return ' ';
}
export async function writeTmpFile(data: string | Buffer, filename?: string, extension?: string): Promise<string> {
const file = `${filename ? filename + '-' : ''}${randomBytes(8).toString('hex')}${extension ? '.' + extension : (typeof data === 'string' ? '.txt' : '')}`;
const path = join(tmpdir(), file);
await fsp.writeFile(path, data);
return path;
}
export function pickRandom<T>(list: T[]): T {
return list[Math.floor(Math.random() * list.length)];
}
// WE OUT HERE
export type Either<L,R> = Left<L> | Right<R>
export class Left<L> {
constructor(private readonly value: L) {}
public getValue() { return this.value; }
}
export class Right<R> {
constructor(private readonly value: R) {}
public getValue() { return this.value; }
}