92 lines
2.0 KiB
TypeScript
92 lines
2.0 KiB
TypeScript
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;
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
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;
|
|
} |