66 lines
1.4 KiB
TypeScript
66 lines
1.4 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;
|
|
}
|