functional/comparison.ts

47 lines
1.2 KiB
TypeScript

import { identity } from "./composition.ts";
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;
}
};
}
/**
* Get a function to check the strict equality with a reference
*/
export function is<T, S extends T>(
ref: T,
): (input: S) => input is Extract<T, S> {
return (x): x is Extract<T, S> => x === ref;
}
/**
* Convert a value to a boolean (are considered falsy: 0, false, "", {}, [], null, undefined)
*/
export function bool<T>(value: T | null | undefined): value is T;
export function bool(value: any): boolean {
if (!value) {
return false;
} else if (value instanceof Set) {
return value.size > 0;
} else if (typeof value == "object") {
return Object.keys(value).length > 0;
} else {
return true;
}
}