Add comments for prelude/array.ts

This commit is contained in:
Aya Morisawa 2018-12-19 09:54:45 +09:00
parent 534de24406
commit 2ee438dece
No known key found for this signature in database
GPG Key ID: 3E64865D70D579F2
1 changed files with 33 additions and 0 deletions

View File

@ -1,19 +1,35 @@
/**
* Count the number of elements that satisfy the predicate
*/
export function countIf<T>(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<T>(x: T, xs: T[]): number {
return countIf(y => x === y, xs);
}
/**
* Concatenate an array of arrays
*/
export function concat<T>(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<T>(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<T>(x: T, xs: T[]): T[] {
return xs.filter(y => x !== y);
}
@ -26,6 +42,9 @@ export function difference<T>(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<T>(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<T>(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<T>(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<T, S>(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<T>(f: (x: T) => boolean, xs: T[]): T[] {
const ys = [];
for (const x of xs) {