aoc/_utils/index.ts

84 lines
1.8 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] : []]
: [
...previousValue.slice(0, -1),
[...previousValue[previousValue.length - 1], currentValue],
];
},
[[]] 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);
}