Add jsdoc and unit tests for util functions

This commit is contained in:
2024-12-02 14:10:59 +01:00
parent 618fbe0102
commit e8b91bae4f
4 changed files with 192 additions and 11 deletions
+40 -11
View File
@@ -1,21 +1,41 @@
export function sumArray(arr: Array<number>): number {
/**
* Returns the sum of all the elements of a numeric array.
* @param arr Numeric array.
*/
export function sumArray(arr: ReadonlyArray<number>): number {
return sumBy(arr, (a) => a);
}
export function sumBy<T>(
arr: Array<T>,
by: (array: T) => number | string
/**
* Returns the sum of all the elements of any array,
* given a lamda function to receive the numeric representation of each element.
* @param arr Any array.
* @param by Map element to number or string, which will be interpreted as a number.
*/
export function sumBy<E>(
arr: ReadonlyArray<E>,
by: (element: E) => number | string
): number {
return arr.reduce((sum, element) => sum + Number(by(element)), 0);
}
export function multArray(arr: Array<number>): number {
/**
* Returns the product of a numeric array.
* @param arr Numeric array.
*/
export function multArray(arr: ReadonlyArray<number>): number {
return multBy(arr, (a) => a);
}
export function multBy<T>(
arr: Array<T>,
by: (array: T) => number | string
/**
* Returns the product of any array,
* given a lamda function to receive the numeric representation of each element.
* @param arr Any array.
* @param by Map element to number or string, which will be interpreted as a number.
*/
export function multBy<E>(
arr: ReadonlyArray<E>,
by: (element: E) => number | string
): number {
if (arr.length <= 0) {
return 0;
@@ -23,19 +43,28 @@ export function multBy<T>(
return arr.reduce((sum, element) => sum * Number(by(element)), 1);
}
/**
* Group an array by a given key.
* @param arr Any array.
* @param by Map element to key.
* @param equals Check if two keys are identical. Defaults to strict equality.
*/
export function groupBy<E, K>(
arr: Array<E>,
by: (element: E) => K
arr: ReadonlyArray<E>,
by: (element: E) => K,
equals: (a: K, b: K) => boolean = (a, b) => a === b
): { key: K; elements: Array<E> }[] {
return arr.reduce(
(groups, element) => {
const key = by(element);
const index = groups.findIndex((e) => e.key === key);
const index = groups.findIndex((e) => equals(e.key, key));
if (index < 0) {
// New key found, add to group array.
groups.push({ key, elements: [element] });
return groups;
}
const existing = groups[index];
existing.elements.push(element);