aoc/_utils/index.ts

92 lines
2.0 KiB
TypeScript
Raw Normal View History

2022-12-03 22:11:42 +00:00
import { readFile } from "fs";
/**
*
* @param filename {string} - name of the filename to read
* @returns - a Promise containing a list of newline-separated strings
*/
export function readlines(
filename: string,
filter?: (value: string) => unknown
): Promise<string[]> {
return new Promise((resolve, reject) => {
readFile(filename, "utf8", function (err, data) {
if (err) {
reject(err);
}
const lines = data.split("\n");
if (filter) {
resolve(lines.filter(filter));
} else {
resolve(lines);
}
});
});
}
export function group<T>(
lines: T[],
cutoffPredicate: (
previousValue: T[][],
currentValue: T,
currentIndex: number,
array: T[]
) => boolean,
includeCutoffValue: boolean = true
): T[][] {
return lines.reduce(
(previousValue, currentValue, currentIndex, array) => {
const isCutoffPoint = cutoffPredicate(
previousValue,
currentValue,
currentIndex,
array
);
return isCutoffPoint
? [...previousValue, includeCutoffValue ? [currentValue] : []]
: [
2023-12-10 20:19:14 +00:00
...previousValue.slice(0, -1),
[...previousValue[previousValue.length - 1], currentValue],
];
2022-12-03 22:11:42 +00:00
},
[[]] as T[][]
);
}
export function sum(a: number, b: number): number {
return a + b;
}
export function emptyLines(line?: string): boolean {
return !!line;
}
2023-12-02 01:57:47 +00:00
export function unique<T>(arr: T[]): T[] {
return arr.reduce<T[]>((res, current) => {
if (res.includes(current)) {
return res;
} else {
return [...res, current];
}
}, []);
}
export function allIndicesOf(s: string, search: string): number[] {
return unique(
s
.split("")
.reduce((results, _, index) => [...results, s.indexOf(search, index)], [])
).filter((x: number) => x >= 0);
}
2023-12-10 20:19:14 +00:00
export function extractNumbers(s: string): number {
const res = s.replaceAll(/[^\d]/g, "").trim()
if (isNaN(+res)) {
throw new Error(`Could not extract numbers from '${s}': got '${res}'`)
}
return +res;
}