40 lines
1.1 KiB
TypeScript
40 lines
1.1 KiB
TypeScript
/**
|
|
* Functions that does nothing (useful for default callbacks)
|
|
*/
|
|
export function nop(...args: any[]): any {
|
|
}
|
|
|
|
/**
|
|
* Identity function (returns the sole argument untouched)
|
|
*/
|
|
export function identity<T>(input: T): T {
|
|
return input;
|
|
}
|
|
|
|
/**
|
|
* Partially apply fixed arguments to a function with named arguments
|
|
*/
|
|
export function partial<A extends object, PA extends Partial<A>, RA extends any[], R>(fixedargs: PA, func: (args: A, ...rest: RA) => R): (args: Omit<A, keyof PA>, ...rest: RA) => R {
|
|
return (args: Omit<A, keyof PA>, ...rest: RA) => func({ ...fixedargs, ...args } as any, ...rest);
|
|
}
|
|
|
|
type cmpArgs = Readonly<{ key: (item: any) => any, reverse: boolean }>
|
|
const cmpDefaults: cmpArgs = { key: identity, reverse: false }
|
|
/**
|
|
* Compare operator, that can be used in sort() calls.
|
|
*/
|
|
export function cmp(args?: Partial<cmpArgs>): (a: any, b: any) => number {
|
|
const fargs = { ...cmpDefaults, ...args };
|
|
return (a, b) => {
|
|
const ka = fargs.key(a);
|
|
const kb = fargs.key(b);
|
|
if (ka > kb) {
|
|
return fargs.reverse ? -1 : 1;
|
|
} else if (ka < kb) {
|
|
return fargs.reverse ? 1 : -1;
|
|
} else {
|
|
return 0;
|
|
}
|
|
}
|
|
}
|