Home
⚙️

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))
  );
}