mentalHealth/01-Web/packages/utils/common/arrays.ts

125 lines
3.3 KiB
TypeScript
Raw Normal View History

2024-02-18 06:52:01 +00:00
import {
each as TREE_EACH,
exclude as TREE_EXCLUDE,
filter as TREE_FILTER,
map as TREE_MAP,
toRows,
toTree,
type ToTreeOptions,
} from '@zhengxs/js.tree';
/**
*
*
* @template T
* @param {T[]} arr
*/
export function unique<T>(arr: T[]) {
return [...new Set(arr)];
}
/**
*
*
* @param {number[]} arr
*/
export function average(arr: number[]) {
return arr.reduce((a, b) => a + b) / arr.length;
}
/**
*
*
* @export
* @template P extends Obj
* @template R extends Obj = P
* @param {P[]} params
* @param {?ToTreeOptions<R, P>} [options]
* @returns {*}
*/
export function rowsToTree<P extends Obj, R extends Obj = P>(params: P[], options?: ToTreeOptions<R, P>) {
return toTree<R, P>(params, options);
}
/**
*
*
* @export
* @template T extends Obj
* @template U extends Obj
* @param {T[]} data
* @param {?string} [childrenKey]
*/
export function treeToRows<T extends Obj, U extends Obj>(data: T[], childrenKey?: string): U[] {
return toRows<T, U>(data, childrenKey);
}
/**
*
*
* @export
* @template T extends Obj
* @template U extends Obj
* @param {T[]} data
* @param {(data: T, index: number, parents: T[]) => U} callback
* @param {?string} [childrenKey]
*/
export function treeMap<T extends Obj, U extends Obj>(
data: T[],
callback: (data: T, index: number, parents: T[]) => U,
childrenKey?: string,
): U[] {
return TREE_MAP<T, U>(data, callback, childrenKey);
}
/**
*
*
* @export
* @template T extends Obj
* @param {T[]} data
* @param {((data: T, index: number, parents: T[]) => boolean | void)} callback `true`
* @param {?string} [childrenKey]
*/
export function treeEach<T extends Obj>(
data: T[],
callback: (data: T, index: number, parents: T[]) => boolean,
childrenKey?: string,
): T[] {
return TREE_EACH<T>(data, callback, childrenKey);
}
/**
*
*
* @export
* @template T extends Obj
* @param {T[]} data
* @param {(data: T, index: number, parents: T[]) => boolean} callback
* @param {?(string)} [childrenKey]
*/
export function treeFilter<T extends Obj>(
data: T[],
callback: (data: T, index: number, parents: T[]) => boolean,
childrenKey?: string,
): T[] {
return TREE_FILTER(data, callback, childrenKey);
}
/**
*
*
* @export
* @template T extends Obj
* @param {T[]} data
* @param {(data: T, index: number, parents: T[]) => boolean} callback true
* @param {?(string)} [childrenKey]
*/
export function treeExclude<T extends Obj>(
data: T[],
callback: (data: T, index: number, parents: T[]) => boolean,
childrenKey?: string,
): T[] {
return TREE_EXCLUDE(data, callback, childrenKey);
}