UNPKG

tiinvo

Version:

A library of types and utilities for your TypeScript and JavaScript projects

120 lines (119 loc) 2.37 kB
//#endregion /** * A function which returns it's first argument. * * Use it only as a placeholder * * @example * * ```ts * import { Fn } from 'tiinvo' * * Fn.pass(10) // 10 * Fn.pass(20) // 20 * ``` * * @since 4.0.0 */ export const pass = (a) => a; export function cmp(a, b) { const _cmp = (x, y) => { const namea = x.name.toLowerCase(); const nameb = y.name.toLowerCase(); return Math.min(Math.max((x.length > y.length ? 1 : x.length < y.length ? -1 : 0) + (namea > nameb ? 1 : namea < nameb ? -1 : 0), -1), 1); }; if (guard(a) && guard(b)) { return _cmp(a, b); } return (b) => _cmp(b, a); } ; export function eq(a, b) { if (guard(a) && guard(b)) { return a === b && cmp(a, b) === 0; } return (b) => b === a && cmp(b, a) === 0; } //#endregion //#region accessors /** * Returns a function arguments length * * @example * * ```ts * import { Fn } from 'tiinvo' * * Fn.length(Fn.cmp) // 2 * Fn.length(Fn.length) // 1 * ``` * * @param x the function * @returns arguments count * @since 4.0.0 */ export const length = x => x.length; /** * Returns a function's name * * @example * * ```ts * import { Fn } from 'tiinvo' * * Fn.name(Fn.cmp) // 'cmp' * Fn.name(Fn.name) // 'name' * ``` * * @param x the function * @returns the name * @since 4.0.0 */ export const name = x => x.name; //#region guardables /** * Checks if an argument `x` is `AnyFn` * * @example * * ```ts * import { Fn } from 'tiinvo' * * Fn.guard(10) // false * Fn.guard(() => {}) // true * ``` * * @param x the value to guard * @returns * - `true` if `x` is a function * - `false` otherwise * @since 4.0.0 */ export const guard = (x) => typeof x === 'function'; //#endregion //#region mappables /** * Maps a value `a` over a list of `Functors.Mappable<a, b>` and returns an array of the returning values * * @example * * ```ts * import { Fn, Num } from 'tiinvo' * * const m = Fn.map( * Num.add(1), * Num.mul(2), * Num.sub(3), * Num.pow(4), * ) * * m(2) // [3, 4, -1, 16] * ``` * * @param ml a list of unary functions which accept the same argument * @return an array of the returning values of `ml` * @since 4.0.0 */ export const map = (...ml) => (a) => ml.map(f => f(a)); //#endregion