meows
Version:
A kittybin of tools.
78 lines (77 loc) • 2.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Class of static boolean functions for finding whether a value is NOT an
* empty instance of a type.
*/
class notEmpty {
}
notEmpty.arr = x => Array.isArray(x) && Boolean(x.length);
notEmpty.obj = x => typeName(x) === 'object' && Boolean(Object.keys(x).length);
notEmpty.str = x => typeof x === 'string' && Boolean(x.length);
notEmpty.map = x => x instanceof Map ? Boolean(x.size) : false;
exports.notEmpty = notEmpty;
/**
* Class of static boolean functions for finding whether a value is an empty
* instance of a type.
*/
class isEmpty {
}
isEmpty.arr = x => Array.isArray(x) && !x.length;
isEmpty.obj = x => typeName(x) === 'object' && !Object.keys(x).length;
isEmpty.str = x => typeof x === 'string' && !x.length;
isEmpty.map = x => x instanceof Map ? !x.size : false;
exports.isEmpty = isEmpty;
/**
* Class of static boolean functions for determining types and non-canonical
* subtypes in JavaScript, such as natural or signable numbers.
*/
class isType {
}
/** All numbers except for `NaN` and `Infinity`. */
isType.num = x => typeof x === 'number' && !Number.isNaN(x) && Number.isFinite(x);
/** Checks if natural number, including zero. */
isType.nat = x => Number.isSafeInteger(x) && 0 <= x;
isType.int = Number.isSafeInteger;
isType.str = x => typeof x === 'string';
/** Check if function. */
isType.fn = x => typeof x === 'function';
/** Any signable number including `0` and `Infinity`, but excluding `NaN`. */
isType.signable = x => typeof x === 'number' && !Number.isNaN(x);
isType.err = x => typeName(x) === 'error';
/** Checks if value is negative, but excludes `0` and `Infinity`. */
isType.neg = x => typeof x === 'number' && !Number.isNaN(x) && Number.isFinite(x) && Math.sign(x) === -1;
isType.map = x => x instanceof Map;
exports.isType = isType;
/**
* Returns the type of an unknown value as a lower-cased string. Type 'number'
* is differentiated from 'nan' and 'infinity' because most numerical functions
* don't expect them.
*
* @example
* typeName(new Map) // => 'map'
* typeName(null) // => 'null'
* typeName([]) // => 'array'
* typeName({}) // => 'object'
* typeName(/\s+/) // => 'regexp'
* typeName(NaN) // => 'nan'
* typeName(-1/0) // => 'infinity'
*/
function typeName(x) {
const type = Object.prototype.toString.call(x).slice(8, -1).toLowerCase();
if (type === 'number') {
if (Number.isNaN(x))
return 'nan';
if (!Number.isFinite(x))
return 'infinity';
else
return type;
}
else
return type;
}
exports.typeName = typeName;
exports.assert = (item, tests, callback) => {
if (!tests.every(isType.fn))
throw new TypeError(`assert() input error`);
};