diff --git a/src/prelude/array.ts b/src/prelude/array.ts index aefc7b3a5b..00f0dc3445 100644 --- a/src/prelude/array.ts +++ b/src/prelude/array.ts @@ -1,19 +1,35 @@ +/** + * Count the number of elements that satisfy the predicate + */ export function countIf(f: (x: T) => boolean, xs: T[]): number { return xs.filter(f).length; } +/** + * Count the number of elements that is equal to the element + */ export function count(x: T, xs: T[]): number { return countIf(y => x === y, xs); } +/** + * Concatenate an array of arrays + */ export function concat(xss: T[][]): T[] { return ([] as T[]).concat(...xss); } +/** + * Intersperse the element between the elements of the array + * @param sep The element to be interspersed + */ export function intersperse(sep: T, xs: T[]): T[] { return concat(xs.map(x => [sep, x])).slice(1); } +/** + * Returns the array of elements that is not equal to the element + */ export function erase(x: T, xs: T[]): T[] { return xs.filter(y => x !== y); } @@ -26,6 +42,9 @@ export function difference(xs: T[], ys: T[]): T[] { return xs.filter(x => !ys.includes(x)); } +/** + * Remove all but the first element from every group of equivalent elements + */ export function unique(xs: T[]): T[] { return [...new Set(xs)]; } @@ -38,6 +57,10 @@ export function maximum(xs: number[]): number { return Math.max(...xs); } +/** + * Splits an array based on the equivalence relation. + * The concatenation of the result equals to the argument. + */ export function groupBy(f: (x: T, y: T) => boolean, xs: T[]): T[][] { const groups = [] as T[][]; for (const x of xs) { @@ -50,10 +73,17 @@ export function groupBy(f: (x: T, y: T) => boolean, xs: T[]): T[][] { return groups; } +/** + * Splits an array based on the equivalence relation induced by the function. + * The concatenation of the result equals to the argument. + */ export function groupOn(f: (x: T) => S, xs: T[]): T[][] { return groupBy((a, b) => f(a) === f(b), xs); } +/** + * Compare two arrays by lexicographical order + */ export function lessThan(xs: number[], ys: number[]): boolean { for (let i = 0; i < Math.min(xs.length, ys.length); i++) { if (xs[i] < ys[i]) return true; @@ -62,6 +92,9 @@ export function lessThan(xs: number[], ys: number[]): boolean { return xs.length < ys.length; } +/** + * Returns the longest prefix of elements that satisfy the predicate + */ export function takeWhile(f: (x: T) => boolean, xs: T[]): T[] { const ys = []; for (const x of xs) {