Utilities module
I practice YAGNI, but I always rewrite these every day so... I'm GNI.
๐ stdin
export function stdin() {
return fs
.readFileSync(0, "utf-8")
}๐ strings
Get strings from stdin, one per line.
export function strings() {
return strings().split("\n");
}๐ paragraphs
Get "paragraphs" from stdin: text separated by empty lines.
export function paragraphs() {
return stdin().split("\n\n");
}๐ numbers
Get numbers from stdin, one per line.
export function numbers() {
return strings().map((s) => parseInt(s));
}๐ sum
Sum an array of numbers (how is this not in the standard library?)
export function sum(ls: number[]) {
return ls.reduce((sum, n) => sum + n);
}๐ permutations
Get all possible rearrangements of a list
export function permutations<T>(
arr: T[]
): T[][] {
if (arr.length === 0) {
return [[]];
} else {
return arr.flatMap((value, idx) => {
const tail = permutations([
...arr.slice(0, idx),
...arr.slice(idx + 1),
]);
return tail.map((sub) => [
value,
...sub,
]);
});
}
}๐ equals
Determine if two sets contain the same elements
export function equals<T>(
a: Set<T>,
b: Set<T>
): boolean {
return (
a.size === b.size &&
[...a].every((val) => b.has(val))
);
}