chek
Version:
Minimal utility for checking types, working with arrays and objects.
1,718 lines (1,709 loc) • 135 kB
JavaScript
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./modules/array"), exports);
__exportStar(require("./modules/constant"), exports);
__exportStar(require("./modules/from"), exports);
__exportStar(require("./modules/function"), exports);
__exportStar(require("./modules/is"), exports);
__exportStar(require("./modules/object"), exports);
__exportStar(require("./modules/string"), exports);
__exportStar(require("./modules/to"), exports);
__exportStar(require("./modules/type"), exports);
},{"./modules/array":3,"./modules/constant":4,"./modules/from":5,"./modules/function":6,"./modules/is":7,"./modules/object":8,"./modules/string":9,"./modules/to":10,"./modules/type":11}],2:[function(require,module,exports){
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
/* Import all methods in case need to add to window */
var chek = require("./chek");
/* istanbul ignore if */
chek.toWindow('chek', chek, ['tryRequire', 'isNode']);
__exportStar(require("./types"), exports);
__exportStar(require("./modules/array"), exports);
__exportStar(require("./modules/constant"), exports);
__exportStar(require("./modules/from"), exports);
__exportStar(require("./modules/function"), exports);
__exportStar(require("./modules/is"), exports);
__exportStar(require("./modules/object"), exports);
__exportStar(require("./modules/string"), exports);
__exportStar(require("./modules/to"), exports);
__exportStar(require("./modules/type"), exports);
exports.default = chek;
},{"./chek":1,"./modules/array":3,"./modules/constant":4,"./modules/from":5,"./modules/function":6,"./modules/is":7,"./modules/object":8,"./modules/string":9,"./modules/to":10,"./modules/type":11,"./types":12}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unshift = exports.splice = exports.shift = exports.push = exports.pop = exports.last = exports.includesAny = exports.includes = exports.first = exports.flatten = exports.keys = exports.duplicates = exports.containsAny = exports.contains = exports.orderBy = void 0;
var is_1 = require("./is");
function defComparator(a, b) { return a < b ? -1 : a > b ? 1 : 0; }
function normComparator(primer, order) {
var comp = defComparator;
var reverse = false;
if (primer)
comp = function (a, b) { return defComparator(primer(a), primer(b)); };
if (order && /^(desc|descending|-1|true)/.test(order + ''))
return function (a, b) {
return -1 * comp(a, b);
};
return comp;
}
/**
* Orders arrays of objects by property, falls back to .sort() if not fields are specified.
*
* @example
* const arr = [{ name: 'bob', age: 30 }, { name: 'john', age: 22 }];
* chek.orderBy(arr, 'age', 'name');
* check.orderBy(arr, { key: 'name', order: 'desc', primer: primerFunc });
* chek.orderBy(arr, 'age', 'name', primerFunc);
*
* Order property: asc, ascending, desc, descending, 1, -1, 0
* Primer property: a method that accepts single value and is run as a preprocessor before sorting.
*
* @param arr the collection to be sorted.
* @param fields an array of field names or comparator field objects.
*/
function orderBy(arr) {
var fields = [];
for (var _i = 1; _i < arguments.length; _i++) {
fields[_i - 1] = arguments[_i];
}
var primer = function (v) { return v; };
// Allows common primer function to be last arg in fields.
if (is_1.isFunction(last(fields)))
primer = (fields.pop());
if (!fields.length) {
var hasNumbers_1 = is_1.isNumber(first(arr)) && is_1.isNumber(last(arr));
return arr.sort(function (a, b) {
a = primer(a);
b = primer(b);
if (hasNumbers_1)
return a - b;
a += '';
b += '';
if (a < b)
return -1;
else if (a > b)
return 1;
else
/* istanbul ignore next */
return 0;
});
}
fields = fields.map(function (f) {
var field = f;
if (is_1.isString(field)) {
field = { key: f };
field.order = /^-/.test(f + ''); // if prefixed with - is reversed.
}
else if (is_1.isArray(field)) {
field = { key: f[0] };
field.order = f[1];
}
field.primer = field.primer || primer;
field.comparator = normComparator(field.primer, field.order);
return field;
});
var comparator = function (a, b) {
var result;
for (var _i = 0, _a = fields; _i < _a.length; _i++) {
var field = _a[_i];
result = field.comparator(a[field.key], b[field.key]);
if (result !== 0)
break;
}
return result;
};
return arr.sort(comparator);
}
exports.orderBy = orderBy;
/**
*
* Contains
* Tests if array contains value.
*
* @param arr the array to be inspected.
* @param value the value to check if is contained in array.
*/
function contains(arr, value, transform) {
arr = arr || [];
if (is_1.isString(arr))
arr = arr.split('');
return arr.filter(function (v) {
if (transform)
v = transform(v);
return is_1.isEqual(v, value);
}).length > 0;
}
exports.contains = contains;
/**
* Contains Any
* Tests array check if contains value.
*
* @param arr the array to be inspected.
* @param compare - array of values to compare.
*/
function containsAny(arr, compare, transform) {
if (is_1.isString(arr))
arr = arr.split('');
if (is_1.isString(compare))
compare = compare.split('');
if (!is_1.isArray(arr) || !is_1.isArray(compare))
return false;
return compare.filter(function (c) {
return contains(arr, c, transform);
}).length > 0;
}
exports.containsAny = containsAny;
/**
* Duplicates
* Counts the number of duplicates in an array.
*
* @param arr the array to check for duplicates.
* @param value the value to match.
* @param breakable when true allows breaking at first duplicate.
*/
function duplicates(arr, value, breakable) {
var i = arr.length;
var dupes = 0;
while (i--) {
if (breakable && dupes > 0)
break;
if (is_1.isEqual(arr[i], value))
dupes += 1;
}
return dupes;
}
exports.duplicates = duplicates;
/**
* Keys
* Takes an object then returns keys in array.
*
* @param obj the object to parse keys.
*/
function keys(obj) {
if (!is_1.isObject(obj))
return [];
return Object.keys(obj);
}
exports.keys = keys;
/**
* Flatten
* Takes multiple arrays and flattens to single array.
* NOTE: this will NOT work for empty nested arrays
* but will work for 90 plus % of cases.
*
* @param args rest param containing multiple arrays to flatten.
*/
function flatten() {
var arr = [];
for (var _i = 0; _i < arguments.length; _i++) {
arr[_i] = arguments[_i];
}
var i = 0;
var result = [];
while (i < arr.length) {
var itm = arr[i];
if (is_1.isArray(itm))
result = result.concat(flatten.apply(void 0, itm));
else
result = result.concat([itm]);
i++;
}
return result;
}
exports.flatten = flatten;
/**
* First
* Simple method to get first element just
* a little less typing.
*
* @param arr the array to get first element from.
*/
function first(arr) {
return arr[0];
}
exports.first = first;
/**
*
* Includes
* Tests if array contains value.
*
* @param arr the array to be inspected.
* @param value the value to check if is contained in array.
*/
/* istanbul ignore next */
function includes(arr, value, transform) {
return contains(arr, value, transform);
}
exports.includes = includes;
/**
*
* Includes Any
* Tests if array contains any value.
*
* @param arr the array to be inspected.
* @param compare the array to compare.
*/
/* istanbul ignore next */
function includesAny(arr, compare, transform) {
return containsAny(arr, compare, transform);
}
exports.includesAny = includesAny;
/**
* Last
* Simple method to get last element.
*
* @param arr the array to get last element.
*/
function last(arr) {
return (arr && arr[arr.length - 1]) || undefined;
}
exports.last = last;
// NOTE: the following are immutable methods.
/**
* Pop
* Pops/removes last element in array.
*
* @param arr the array to pop value from.
*/
function pop(arr) {
return {
array: arr.slice(0, arr.length - 1),
val: arr[arr.length - 1]
};
}
exports.pop = pop;
/**
* Push
* Non mutating way to push to an array.
*
* @param arr the array to push items to.
* @param args the items to be added.
*/
function push(arr) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
arr = arr.concat(flatten.apply(void 0, args));
return {
array: arr,
val: arr.length
};
}
exports.push = push;
/**
* Shift
* Shifts/removes first element in array.
* As this is a non-mutating method returns
* an object with new array and shifted value.
*
* @param arr the array to shift value from.
*/
function shift(arr) {
var shifted = splice(arr, 0, 1);
return {
array: shifted.array,
val: arr[0]
};
}
exports.shift = shift;
/**
* Splice
* Non mutating way of splicing an array.
*
*
* @param arr the array to be spliced.
* @param start the starting index (default: 0)
* @param remove the count to be spliced (default: 1)
* @param items additional items to be concatenated.
*/
function splice(arr, start, remove) {
var items = [];
for (var _i = 3; _i < arguments.length; _i++) {
items[_i - 3] = arguments[_i];
}
start = start || 0;
var head = arr.slice(0, start);
var tail = arr.slice(start);
var removed = [];
if (remove) {
removed = tail.slice(0, remove);
tail = tail.slice(remove);
}
if (!is_1.isValue(remove)) {
arr = head.concat(items);
removed = tail;
}
else {
arr = head.concat(items).concat(tail);
}
return {
array: arr,
val: removed
};
}
exports.splice = splice;
/**
* Unshift
* Unshifts a value to an array in a non mutable way.
*
* @param arr the array to be unshifted.
* @param value the value to be unshifted
*/
function unshift(arr) {
var items = [];
for (var _i = 1; _i < arguments.length; _i++) {
items[_i - 1] = arguments[_i];
}
arr = arr.concat(flatten(items));
return {
array: arr,
val: arr.length
};
}
exports.unshift = unshift;
},{"./is":7}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toStr = void 0;
exports.toStr = Object.prototype.toString;
},{}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.fromJSON = exports.fromEpoch = void 0;
var is_1 = require("./is");
var function_1 = require("./function");
var to_1 = require("./to");
/**
* From Epoch
* Converts to a Date from an epoch.
*
* @param val the epoch value to convert to date.
*/
function fromEpoch(val, def) {
if (!is_1.isValue(val) || !is_1.isNumber(val))
return to_1.toDefault(null, def);
return new Date(val);
}
exports.fromEpoch = fromEpoch;
/**
* From JSON
* Simple wrapper to parse json.
* @alias tryParseJSON
*
* @param val the string to be parsed.
* @param def a default fallback value on failed parse.
*/
function fromJSON(val, def) {
return function_1.tryWrap(JSON.parse, val)(def);
}
exports.fromJSON = fromJSON;
},{"./function":6,"./is":7,"./to":10}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tryRootRequire = exports.tryRequire = exports.tryWrap = exports.noopIf = exports.noop = void 0;
var is_1 = require("./is");
var to_1 = require("./to");
/* istanbul ignore next */
/**
* Noop
*/
function noop() {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
}
exports.noop = noop;
/**
* Noop If
* If function provided return no operation funciton.
*
* @param fn optional function.
*/
function noopIf(fn) {
return fn || noop;
}
exports.noopIf = noopIf;
/**
* Try Wrap
* Generic helper for calling try catch on a method.
* If a default method is provided it will return in on error
* otherwise it will return null.
*
* @example
* function func(val: any) { return isString(val); }
* const result = tryWrap(func)();
*
* With params
* tryWrap(JSON.stringify, { name: 'Adele', age: 30 }, null, 2)()
*
* With default
* tryWrap(Number, '30')(35);
* Where '35' is the default value on error.
*
* @param fn the parse method to be called in try/parse block.
* @param args arguments to pass to above method.
*/
function tryWrap(fn) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
return function (def) {
try {
return fn.apply(void 0, args);
}
catch (ex) {
if (is_1.isFunction(def))
return def(ex);
return to_1.toDefault(def);
}
};
}
exports.tryWrap = tryWrap;
/**
* Try Require
* Tries to require a module returns null
* if cannot require or empty object.
*
* @param name the name of module to try and require.
* @param def optional default value on null.
* @param isRoot used internally by tryRootRequire to require root modules.
*/
function tryRequire(name, def, isRoot) {
function _require() {
if (!is_1.isNode())
/* istanbul ignore next */
return to_1.toDefault(null, def);
if (isRoot)
return require.main.require(name);
return require(name);
}
return tryWrap(_require)(def);
}
exports.tryRequire = tryRequire;
/**
* Try Root Require
* Tries to require module relative from root module.
*
* @param name the name of the module to try and require.
* @param def the default value if null.
*/
function tryRootRequire(name, def) {
return tryRequire(name, def);
}
exports.tryRootRequire = tryRootRequire;
},{"./is":7,"./to":10}],7:[function(require,module,exports){
(function (process,Buffer){(function (){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isWindows = exports.isValue = exports.isUnique = exports.isUndefinedOrNull = exports.isUndefined = exports.isType = exports.isTruthy = exports.isSymbol = exports.isString = exports.isRoot = exports.isRegExp = exports.isPromise = exports.isPlainObject = exports.isObject = exports.isMoment = exports.isNumber = exports.isNull = exports.isNode = exports.isInteger = exports.isInspect = exports.isInfinite = exports.isFunction = exports.isFloat = exports.isDocker = exports.isDirectory = exports.isFile = exports.isError = exports.isEqual = exports.isEmpty = exports.isDebug = exports.isDate = exports.isBuffer = exports.isBrowser = exports.isBoolean = exports.isArray = void 0;
var constant_1 = require("./constant");
var to_1 = require("./to");
var function_1 = require("./function");
var array_1 = require("./array");
var existsSync, statSync, readFileSync;
if (isNode()) {
var fs = require('fs');
existsSync = fs.existsSync.bind(fs);
statSync = fs.statSync.bind(fs);
readFileSync = fs.readFileSync.bind(fs);
}
/**
* Is Array
* Check if value is an array.
*
* @param val the value to test if is array.
*/
function isArray(val) {
/* istanbul ignore if */
if (!Array.isArray)
return constant_1.toStr.call(val) === '[object Array]';
return Array.isArray(val);
}
exports.isArray = isArray;
/**
* Is Boolean
*
* @param val
*/
function isBoolean(val) {
return isValue(val) && typeof val === 'boolean';
}
exports.isBoolean = isBoolean;
/**
* Is Browser
* Checks if script is running in browser.
*
* @param override an optional key to inspect on process.env.
*/
function isBrowser(override) {
// Enables checking a process.env key while
// in Node.
if (override)
return typeof process !== 'undefined' &&
function_1.tryWrap(to_1.toBoolean, process.env &&
process.env[override])(false) === true;
// Otherwise just return NOT Node.
return !isNode();
}
exports.isBrowser = isBrowser;
/**
* Is Buffer
* Checks if value is an instanceof Buffer.
*
* @param val the value to inspect as Buffer.
*/
function isBuffer(val) {
return isValue(val) && (val instanceof Buffer);
}
exports.isBuffer = isBuffer;
/**
* Is Date
* Inspects if is Date, parses date string when
* parse flag is set to true.
*
* @param val the value to inspect/test if is Date.
* @param parse when true the value is parsed to see if is date.
*/
function isDate(val) {
return (isValue(val) &&
val.constructor &&
val.constructor === Date);
}
exports.isDate = isDate;
/**
* Indicates if app is in debug mode.
* @param debugging a manual flag to denote debugging.
*/
function isDebug(debugging) {
// If manually passed just return.
if (isValue(debugging))
return debugging;
var eargv = process && process.execArgv;
function chkDebug() {
return (eargv.filter(function (v) { return /^(--debug|--inspect)/.test(v); }).length ||
isValue(v8debug));
}
return function_1.tryWrap(chkDebug)(false);
}
exports.isDebug = isDebug;
/**
* Is Empty
* Test if value provided is empty.
* Note 0 would be empty.
*
* @param val value to be inspected.
*/
function isEmpty(val) {
return (isUndefined(val) ||
isNull(val) ||
(isString(val) && val.length === 0) ||
(isNumber(val) && isNaN(val)) ||
(isPlainObject(val) && !array_1.keys(val).length) ||
(isArray(val) && !val.length));
}
exports.isEmpty = isEmpty;
/**
* Is Equal
* Tests if two values are equal.
* Does not support "deep equal".
*
* @param val the value to be compared.
* @param comp the comparer value.
* @param loose when true == is used instead of ===.
*/
function isEqual(val, comp, loose) {
if (isDate(val) && isDate(comp))
return to_1.toEpoch(val) === to_1.toEpoch(comp);
if (loose)
return val == comp;
return val === comp;
}
exports.isEqual = isEqual;
/**
* Is Error
* Checks if value is an error. Allows custom error property
* which can be useful in certain scenarios to flag an object
* as an error.
*
* @param val the value/object to be inspected.
* @param prop a custom property to check if exists indicating is error.
*/
function isError(val, prop) {
if (!isValue(val) || !isObject(val))
return false;
var type = constant_1.toStr.call(val).toLowerCase();
return type === '[object error]' || type === '[object domexception]' || !isEmpty(val[prop]);
}
exports.isError = isError;
/**
* Is File
* Checks if value is path to file in filesytem.
* NODE ONLY!
*
* @param val the value to inspect as file.
*/
function isFile(val) {
return (isNode() &&
existsSync(val) &&
statSync(val).isFile());
}
exports.isFile = isFile;
/**
* Is Directory
* Checks if value is path to directory in filesytem.
* NODE ONLY!
*
* @param val the value to inspect as file.
*/
function isDirectory(val) {
return (isNode() &&
existsSync(val) &&
statSync(val).isDirectory());
}
exports.isDirectory = isDirectory;
/**
* Is Docker
* Checks if running inside Docker container.
*/
function isDocker() {
if (!isNode())
return false;
var hasEnv = function_1.tryWrap(function () {
statSync('/.dockerenv');
return true;
})(false);
var hasGroup = function_1.tryWrap(function () {
return ~readFileSync('/proc/self/cgroup', 'utf8').indexOf('docker');
})(false);
return hasEnv || hasGroup;
}
exports.isDocker = isDocker;
/**
* Is Float
* Checks if number is float.
*
* @param val the value to inspect.
*/
function isFloat(val) {
return (isNumber(val) &&
Number(val) === val && val % 1 !== 0);
}
exports.isFloat = isFloat;
/**
* Is Function
* Check if object provided is function.
*
* @param val - test object provided is function.
*/
function isFunction(val) {
return isValue(val) && typeof val === 'function';
}
exports.isFunction = isFunction;
/**
* Is Infinite
* Checks if value is Infinity.
*
* @param val the value to test if infinite.
*/
function isInfinite(val) {
return val === Infinity;
}
exports.isInfinite = isInfinite;
/**
* Indicates if app is started with --inspect flag.
*
* @param inspecting a manual flag to denote inspecting.
*/
function isInspect(inspecting) {
// If manually passed just return.
if (isValue(inspecting))
return inspecting;
var eargv = process && process.execArgv;
function chkInspect() {
return (eargv.indexOf('--inspect') !== -1 ||
eargv.indexOf('--inspect-brk') !== -1);
}
return function_1.tryWrap(chkInspect)(false);
}
exports.isInspect = isInspect;
/**
* Is Integer
* Checks if numbers is an integer.
*
* @param val the value to inspect.
*/
function isInteger(val) {
return (isNumber(val) &&
(val % 1 === 0));
}
exports.isInteger = isInteger;
/**
* Is Node
* Tests if is NodeJS.
*/
function isNode() {
return typeof module !== 'undefined' &&
module.exports &&
typeof window === 'undefined';
}
exports.isNode = isNode;
/**
* Is Null
* Checks if value is null.
*
* @param val the object to inspect for null.
*/
function isNull(val) {
return val === null;
}
exports.isNull = isNull;
/**
* Check if value provided is number.
* @param val the value to be tested.
*/
function isNumber(val) {
return !isObject(val) && !isNaN(parseFloat(val)) && isFinite(val);
}
exports.isNumber = isNumber;
/**
* Is Moment
* Inspects object to detect if is moment.
*
* @param val the object to be inspected.
*/
function isMoment(val) {
return isObject(val) && val._isAMomentObject;
}
exports.isMoment = isMoment;
/**
* Is Object
* Checks if value is an object.
*
* @param val the value to inspect.
*/
function isObject(val) {
return (!isUndefined(val) &&
!isNull(val) &&
((val && val.constructor === Object) || typeof val === 'function' || typeof val === 'object'));
}
exports.isObject = isObject;
/**
* Is Plain Object
* Inspects value checking if is object literal.
*
* @param val the value to inspect
*/
function isPlainObject(val) {
return val && val.constructor && val.constructor === {}.constructor;
}
exports.isPlainObject = isPlainObject;
/**
* Is Promise
* Checks if value is a Promise.
*
* @param val the value to inspect.
* @param name optional constructor name for promise defaults to Promise.
*/
function isPromise(val, name) {
name = name || 'Promise';
return (!isEmpty(val) &&
val.constructor &&
val.constructor.name === name);
}
exports.isPromise = isPromise;
/**
* Is Reg Expression
* Tests if object is regular expression.
*
* @param val the value to inspect as RegExp.
*/
function isRegExp(val) {
return val && val.constructor && val.constructor === RegExp;
}
exports.isRegExp = isRegExp;
/**
* Is Root
* If Node checks if is running under sudo.
*/
function isRoot() {
if (!isNode())
return false;
return process.getuid() === 0;
}
exports.isRoot = isRoot;
/**
* Is String
* Inspect value provided testing if is string.
* @param val the value to be tested.
*/
function isString(val) {
return isValue(val) && (typeof val === 'string' || val instanceof String);
}
exports.isString = isString;
/**
* Is Symbol
* Checks if value is of type Symbol.
*
* @param val the value to inspect.
*/
function isSymbol(val) {
return isValue(val) && typeof val === 'symbol';
}
exports.isSymbol = isSymbol;
/**
* Is Truthy
* Checks if value is truthy e.g. not false, 0,
* null, undefined, empty.
*
* Strings such as 'false', '0', '-' or 'no'
* will return true. If NOT desired call toBoolean
* on the value then pass to isTruthy.
*
* @param val the value to inspect.
*/
function isTruthy(val) {
if (!isValue(val))
return false;
if (typeof val === 'number')
return val > 0;
if (isString(val) && !val.length)
return false;
return (val !== false &&
val !== isNaN(val));
}
exports.isTruthy = isTruthy;
/**
* Is Type
* Tests if object is instanceof provided Type.
*
* @param val the value to inspect.
* @param Type the instance type to match.
*/
function isType(val, Type) {
return val instanceof Type;
}
exports.isType = isType;
/**
* Is Undefined
* Tests if value is undefined.
*
* @param val the value to inspect
*/
function isUndefined(val) {
return typeof val === 'undefined' || typeof val === undefined;
}
exports.isUndefined = isUndefined;
/**
* Checks if is undefined or null value.
* @param val the value to inspect.
*/
function isUndefinedOrNull(val) {
return isUndefined(val) || isNull(val);
}
exports.isUndefinedOrNull = isUndefinedOrNull;
/**
* Is Unique
* Tests if the value is unique in the collection.
*
* @param arr the array to be inspected.
* @param value the value to be matched.
*/
function isUnique(arr, value) {
return array_1.duplicates(arr, value) === 1;
}
exports.isUnique = isUnique;
/**
* Is Value
* Ensures is of some value, e.g. not null
* not undefined not isNaN & not Infinite.
*
* @param val the value to inspect.
*/
function isValue(val) {
return (!isUndefined(val)
&& !isNull(val) && !(isNumber(val) && isNaN(val))
&& !isInfinite(val));
}
exports.isValue = isValue;
/**
* Is Windows
* Returns boolean if node is running in Windows.
*/
function isWindows() {
if (!isNode() || !(process && process.platform))
/* istanbul ignore next */
return false;
return process.platform.indexOf('win') === 0;
}
exports.isWindows = isWindows;
}).call(this)}).call(this,require('_process'),require("buffer").Buffer)
},{"./array":3,"./constant":4,"./function":6,"./to":10,"_process":19,"buffer":15,"fs":14}],8:[function(require,module,exports){
"use strict";
var __spreadArray = (this && this.__spreadArray) || function (to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.pick = exports.omit = exports.create = exports.set = exports.reverse = exports.put = exports.extend = exports.clone = exports.has = exports.get = exports.del = exports.assign = void 0;
var _clone = require("clone");
var array_1 = require("./array");
var is_1 = require("./is");
var string_1 = require("./string");
var to_1 = require("./to");
var objAssign = require("object-assign");
/**
* Match Index
* @private
*
* @param prop the property to match.
*/
function matchIndex(prop) {
if (!prop || !/\[\d+\]/.test(prop))
return false;
var prefix = prop.match(/[^[]+/i);
var idx;
var indices = prop.match(/\d+/g);
if (!indices)
return false;
return {
name: prefix[0],
index: indices[0],
indices: indices.slice(1)
};
}
/**
* Del
* @private
*/
function _del(obj, key) {
if (arguments.length !== 2 || !is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key)))
return null;
var props = string_1.split(key);
var prop = props.shift();
var match = matchIndex(prop);
var next = obj[prop];
if (match)
next = obj[match.name][match.index];
if (props.length > 0) {
_del(next, props);
}
else {
if (match) {
obj[match.name].splice(match.index, 1);
}
else {
delete obj[prop];
}
}
return obj;
}
/**
* Get
* @private
*/
function _get(obj, key) {
if (!is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key)))
return null;
var props = is_1.isArray(key) ? key : string_1.split(key);
while (props.length && obj) {
var prop = props.shift();
var match = matchIndex(prop);
if (match) {
/* istanbul ignore next */
if (!is_1.isUndefined(obj[match.name])) {
obj = obj[match.name][match.index];
// iterate each indices and set obj to that index.
match.indices.forEach(function (i) { return obj = obj[i]; });
}
}
else {
obj = obj[prop];
}
}
return obj;
}
/**
* Set
* @private
*/
function _set(obj, key, val) {
if (arguments.length !== 3 || !is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key)))
return null;
var props = string_1.split(key);
/* istanbul ignore if */
// if (!isValue(val))
// val = {};
var prop = props.shift();
var match = matchIndex(prop);
var next = obj[prop];
if (!is_1.isValue(next) && !match)
next = obj[prop] = {};
if (match) {
if (!obj[match.name])
obj[match.name] = [];
next = obj[match.name][match.index];
}
if (props.length > 0) {
_set(next, props, val);
}
else {
if (match)
obj[match.name][match.index] = val;
else
obj[prop] = val;
}
return obj;
}
function _put(obj, key, val) {
if (!is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key)))
return null;
// Get current and ensure an array.
var cur = to_1.toArray(get(obj, key), []);
if (!is_1.isArray(val))
val = [val];
return _set(obj, key, __spreadArray(__spreadArray([], cur), val));
}
/**
* Uses Object.assign if available or falls back to polyfill.
*
* @param obj object to assign.
* @param args additional source object.
*/
function assign(obj) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
if (Object.assign)
return Object.assign.apply(Object, __spreadArray([obj], args));
return objAssign.apply(void 0, __spreadArray([obj], args));
}
exports.assign = assign;
/**
* Del
* Removes a property within the supplied object.
*
* @param obj the object to inspect.
* @param key the dot notated key or array of keys.
* @param immutable when true original object NOT mutated.
*/
function del(obj, key, immutable) {
if (immutable)
return _del(assign({}, obj), key);
return _del(obj, key);
}
exports.del = del;
/**
* Get
* Gets a property within the supplied object.
*
* @param obj the object to inspect.
* @param key the dot notated key or array of keys.
* @param def a default value to set if not exists.
*/
function get(obj, key, def) {
var result = _get(assign({}, obj), key);
if (!is_1.isValue(result) && def) {
_set(obj, key, def);
result = def;
}
return result;
}
exports.get = get;
/**
* Has
* Checks if property exists in object.
*
* @param obj the object to be inpsected.
* @param key the key to be found.
*/
function has(obj, key) {
if (!is_1.isObject(obj) || (!is_1.isArray(key) && !is_1.isString(key)))
return false;
obj = assign({}, obj);
var props = is_1.isArray(key) ? key : string_1.split(key);
while (props.length && obj) {
var prop = props.shift();
var match = matchIndex(prop);
if (!props.length) { // no more props chek path.
var _keys = array_1.keys(obj);
if (match) {
return array_1.contains(_keys, match.name) && is_1.isValue(obj[match.name][match.index]);
}
else {
return array_1.contains(_keys, prop);
}
}
if (match) {
/* istanbul ignore next */
if (!is_1.isUndefined(obj[match.name])) {
obj = obj[match.name][match.index];
// iterate each indices and set obj to that index.
match.indices.forEach(function (i) { return obj = obj[i]; });
}
}
else {
obj = obj[prop];
}
}
}
exports.has = has;
/**
* Clone
* Performs deep cloning of objects.
*
* @param obj object to be cloned.
* @param json performs quick shallow clone using JSON.
*/
function clone(obj, json) {
if (json)
return JSON.parse(JSON.stringify(obj));
return _clone(obj);
}
exports.clone = clone;
function extend(obj) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var shallow = false;
var dest = obj;
// Determine if is shallow.
if (is_1.isBoolean(dest)) {
shallow = dest;
if (!args.length)
return {};
// get first arg as destination.
dest = args[0];
args = args.slice(1);
}
// If not an object return.
if (!is_1.isObject(dest))
return dest;
var i = 0;
while (i < args.length) {
var src = args[i];
if (!is_1.isObject(src))
src = {};
var _loop_1 = function (p) {
if (src.hasOwnProperty(p)) {
// Copy only top level props.
if (shallow) {
if (!is_1.isUndefined(src[p]))
dest[p] = src[p];
}
else {
if (is_1.isArray(src[p]) && is_1.isArray(dest[p])) {
// Iterate the array.
src[p].forEach(function (v, idx) {
dest[p][idx] = v;
});
}
else if (is_1.isArray(src[p])) {
dest[p] = src[p];
}
else if (is_1.isPlainObject(src[p])) {
dest[p] = extend(dest[p] || {}, src[p]);
}
else {
if (!is_1.isUndefined(src[p]))
dest[p] = src[p];
}
}
}
};
for (var p in src) {
_loop_1(p);
}
i++;
}
return dest;
}
exports.extend = extend;
/**
* Put a value to key. If the value is not currently an array it converts.
*
* @param obj the object to push value to.
* @param key the key or array of keys to be joined as dot notation.
* @param val the value to be pushed.
* @param immutable when true update in immutable mode.
*/
function put(obj, key, val, immutable) {
if (immutable)
return _put(assign({}, obj), key, val);
return _put(obj, key, val);
}
exports.put = put;
/**
* Reverse
* Reverses arrays, strings or objects.
* Only numbers, strings or booleans are supported
* when reverse mapping objects.
*
* @param obj the object to reverse.
*/
function reverse(obj) {
if (!is_1.isValue(obj))
return null;
// Reverse an array.
if (is_1.isArray(obj))
return obj.reverse();
// Reverse a string.
if (is_1.isString(obj)) {
var i = obj.toString().length;
var tmpStr = '';
while (i--)
tmpStr += obj[i];
return tmpStr;
}
// Reverse an object.
var result = {};
for (var p in obj) {
if (is_1.isObject(obj[p]))
continue;
result[obj[p]] = p;
}
return result;
}
exports.reverse = reverse;
/**
* Set
* Sets a value on an object using dot notation or url path.
*
* @todo need to refactor this method.
*
* @param obj the object to set the value on.
* @param key the property used for setting the value.
* @param value the value used for updating the property.
* @param immutable when true the original object is NOT mutated.
*
*/
function set(obj, key, val, immutable) {
if (immutable)
return _set(assign({}, obj), key, val);
return _set(obj, key, val);
}
exports.set = set;
/**
* Create is a convenience method that simply calls Object.create().
* If no object is passed creates using null.
*
* @param obj optional object to use with Object.create.
*/
function create(obj) {
return Object.create(obj || null);
}
exports.create = create;
function omit(obj, props, immutable) {
props = to_1.toArray(props, []);
if (!is_1.isValue(obj) || (!is_1.isArray(obj) && !is_1.isObject(obj) && !is_1.isString(obj)) || !props || !props.length)
return obj;
props = to_1.toArray(props);
// Note replaces double spaces only after
// removing props from string. Also removes
// space if trailed by any of the following
// punctuation: .!?;,:
if (is_1.isString(obj)) {
return props.reduce(function (a, c) {
if ((c instanceof RegExp))
return a.replace(c, '');
a = (a.slice(0, a.indexOf(c)) + a.slice(a.indexOf(c) + c.length)).replace(/\s{2}/, ' ');
a = a.replace(/\s[.!?;,:]/, a.slice(a.length - 1));
return a;
}, obj);
}
if (is_1.isArray(obj))
return obj.filter(function (v) { return !~props.indexOf(v); });
if (!immutable)
return props.reduce(function (a, c) { return del(a, c); }, obj);
return props.reduce(function (a, c) { return del(a, c, true); }, obj);
}
exports.omit = omit;
/**
* Picks values from object by property name.
*
* @param obj the object to pick from.
* @param props the properties to be picked.
*/
function pick(obj, props) {
props = to_1.toArray(props, []);
if (!is_1.isValue(obj) || !is_1.isObject(obj) || !props || !props.length)
return obj;
return props.reduce(function (a, c) {
var val = get(obj, c, undefined);
if (is_1.isUndefined(val))
return a;
return set(a, c, val);
}, {});
}
exports.pick = pick;
},{"./array":3,"./is":7,"./string":9,"./to":10,"clone":16,"object-assign":18}],9:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uuid = exports.uppercase = exports.titlecase = exports.slugify = exports.split = exports.padValues = exports.padRight = exports.padLeft = exports.lowercase = exports.capitalize = exports.decamelcase = exports.camelcase = void 0;
var is_1 = require("./is");
var to_1 = require("./to");
/**
* Camelcase
* Converts string to camelcase.
*
* @param val the value to be transformed.
*/
function camelcase(val) {
if (!is_1.isValue(val))
return null;
var result = val.replace(/[^A-Za-z0-9]/g, ' ').replace(/^\w|[A-Z]|\b\w|\s+/g, function (m, i) {
if (+m === 0 || /(\.|-|_)/.test(m))
return '';
return i === 0 ? m.toLowerCase() : m.toUpperCase();
});
return result.charAt(0).toLowerCase() + result.slice(1);
}
exports.camelcase = camelcase;
/**
* Decamelcase converts a camelcase string to --some-flag.
*
* @param val the value to de-camelize.
* @param separator the separator char once decamelized.
*/
function decamelcase(val, separator) {
if (separator === void 0) { separator = '-'; }
if (!is_1.isValue(val))
return null;
return val
.replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
.replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
.toLowerCase();
}
exports.decamelcase = decamelcase;
/**
* Capitalize
* Converts string to capitalize.
*
* @param val the value to be transformed.
*/
function capitalize(val) {
if (!is_1.isValue(val))
return null;
val = val.toLowerCase();
return "" + val.charAt(0).toUpperCase() + val.slice(1);
}
exports.capitalize = capitalize;
/**
* Lowercase
* Converts string to lowercase.
*
* @param val the value to be transformed.
*/
function lowercase(val) {
if (!is_1.isValue(val))
return null;
return val.toLowerCase();
}
exports.lowercase = lowercase;
/**
* Pad Left
* Pads a string on the left.
*
* @param val the string to be padded.
* @param len the length to pad.
* @param offset an offset number or string to be counted.
* @param char the character to pad with.
*/
function padLeft(val, len, offset, char) {
/* istanbul ignore if */
if (!is_1.isValue(val) || !is_1.isString(val))
return null;
// If offset is a string
// count its length.
if (is_1.isString(offset))
offset = offset.length;
char = char || ' ';
var pad = '';
while (len--) {
pad += char;
}
if (offset)
return padLeft('', offset, null, char) + pad + val;
return pad + val;
}
exports.padLeft = padLeft;
/**
* Pad Right
* Pads a string to the right.
*
* @param val the string to be padded.
* @param len the length to pad.
* @param offset an offset value to add.
* @param char the character to pad with.
*/
function padRight(val, len, offset, char) {
/* istanbul ignore if */
if (!is_1.isValue(val) || !is_1.isString(val))
return null;
// If offset is a string
// count its length.
if (is_1.isString(offset))
offset = offset.length;
char = char || ' ';
while (len--) {
val += char;
}
if (offset)
val += padRight('', offset, null, char);
return val;
}
exports.padRight = padRight;
/**
* Pad Values
*
* @param values the values to be padded.
* @param dir the direction to pad.
* @param offset an offset value to add.
* @param char the character to pad with.
*/
function padValues(arr, strategy, offset, char) {
/* istanbul ignore if */
if (!is_1.isValue(arr) || !is_1.isArray(arr))
return null;
// If offset is a string
// count its length.
if (is_1.isString(offset))
offset = offset.length;
// do nothing.
if (strategy === 'none')
return arr;
var len = 0;
strategy = strategy || 'right';
char = char || ' ';
var func = strategy === 'right' ? padRight : padLeft;
arr.forEach(function (item) {
if (item.length > len)
len = item.length;
});
if (offset)
len += offset;
arr.forEach(function (item, i) {
if (item.length < len)
arr[i] = func(item, len - item.length, null, char);
});
return arr;
}
exports.padValues = padValues;
/**
* Split
* Splits a string at character.
* Default possible chars to match: ['/', '.', ',', ';', '|']
* Note accepts string[] to simplify external methods that call split
* In this case will simply return the array.
*
* @param val the string to be split.
* @param char the character to split at.
*/
function split(val, chars) {
if (is_1.isArray(val))
return val;
if (!is_1.isValue(val) || !is_1.isString(val))
return null;
// default characters.
var defChars = ['/', '.', ',', ';', '|'];
var char;
chars = chars ? to_1.toArray(chars) : defChars;
// if no char iterate defaults.
var i = 0;
while (i < chars.length && !char) {
if (val.indexOf(chars[i]) !== -1) {
char = chars[i];
}
i++;
}
if (!is_1.isValue(char))
return [val];
var arr = val.split(char).map(function (v) { return v.trim(); });
// If empty remove first element.
// this happens when splitting on
// char and is first char in string.
if (is_1.isEmpty(arr[0]))
arr.shift();
return arr;
}
exports.split = split;
/**
* Slugify
* Slugifies string.
*
* @param val the value to be transformed.
* @param def optional default value on null.
*/
function slugify(val) {
if (!is_1.isValue(val))
return null;
val = val.replace(/^\s+|\s+$/g, '').toLowerCase();
// replace accents etc.
var from = 'ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;';
var to = 'aaaaaeeeeeiiiiooooouuuunc------';
for (var i = 0, l = from.length; i < l; i++) {
val = val.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
val = val.replace(/[^a-z0-9 -]/g, '') // replace invalid chars.
.replace(/\s+/g, '-') // replace whitespace with -
.replace(/-+/g, '-'); // replace multiple dashes with single.
return val;
}
exports.slugify = slugify;
/**
* Titlecase
* Converts string to titlecase.
*
* This fine script refactored from:
* @see https://github.com/gouch/to-title-case
*
* @param val the value to be transformed.
* @param conjunctions when true words like and, a, but, for are also titlecased.
*/
function titlecase(val, conjunctions) {
if (!is_1.isValue(val))
return null;
// conjunctions
var conj = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
return val.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function (m, i, t) {
if (i > 0 && i + m.length !== t.length &&
m.search(conj) > -1 && t.charAt(i - 2) !== ';' &&
(t.charAt(i + m.length) !== '-' || t.charAt(i - 1) === '-') &&
t.charAt(i - 1).search(/[^\s-]/) < 0) {
if (conjunctions === false)
return capitalize(m);
return m.toLowerCase();
}
if (m.substr(1).search(/[A-Z]|\../) > -1)
/* istanbul ignore next */
return m;
return m.charAt(0).toUpperCase() + m.substr(1);
});
}
exports.titlecase = titlecase;
/**
* Uppercase
* Converts string to uppercase.
*
* @param val the value to be transformed.
*/
function uppercase(val) {
if (!is_1.isValue(val))
return null;
return val.toUpperCase();
}
exports.uppercase = uppercase;
/**
* UUID
* Generates a UUID.
*/
function uuid() {
var d = Date.now();
// Use high perf timer if avail.
/* istanbul ignore next */
if (typeof performance !== 'undefined' && is_1.isFunction(performance.now))
d += performance.now();
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
exports.uuid = uuid;
},{"./is":7,"./to":10}],10:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toWindow = exports.toUnnested = exports.toString = exports.toRegExp = exports.toNumber = exports.toNested = exports.toMap = exports.toInteger = exports.toJSON = exports.toFloat = exports.toEpoch = exports.toDefault = exports.toDate = exports.toBoolean = exports.toArray = void 0;
var array_1 = require("./array");
var from_1 = require("./from");
var is_1 = require("./is");
var object_1 = require("./object");
var function_1 = require("./function");
var string_1 = require("./string");
function toArray(val, id, def) {
if (is_1.isArray(id)) {
def = id;
id = undefined;
}
if (!is_1.isValue(val))
return toDefault(null, def || []);
if (is_1.isArray(val))
return val;
var ARRAY_LIKE_EXP = /^(.+(,|\||\s).+){1,}$/;
// id = id || '$id';
if (is_1.isPlainObject(val) && id) {
var arr = [];
for (var p in val) {
if (val.hasOwnProperty(p)) {
var cur = val[p];
if (is_1.isPlainObject(cur)) {
var tmp = {};
tmp[id] = p;
var obj = Object.assign({}, cur, tmp);
arr = array_1.push(arr, obj).array;
}
else {
arr = array_1.push(arr, val).array;
}
}
}
return arr;
}
if (is_1.isString(val) && ARRAY_LIKE_EXP.test(val)) {
var arr = string_1.split(val);
return arr;
}
return [val];
}
exports.toArray = toArray;
/**
* To Boolean
* Converts value if not boolean to boolean.
* Will convert 'true', '1', 'yes' or '+' to true.
*
* @param val the value to inspect.
* @param def optional default value on null.
*/
function toBoolean(val, def) {
if (is_1.isBoolean(val))
return val;
if (!is_1.isValue(val))
return toDefault(null, def);
val = val.toString();
return (parseFloat(val) > 0 ||
is_1.isInfinite(val) ||
val === 'true' ||
val === 'yes' ||
val === '1' ||
val === '+');
}
exports.toBoolean = toBoolean;
/**
* To Date
* Converts value to date using Date.parse when string.
* Optionally you can pass a format object containing
* Intl.DateFormatOptions and locales. You