UNPKG

ntils

Version:

一个 Node & Browser 工具函数集

523 lines (517 loc) 17 kB
var ntils = (function (exports) { 'use strict'; var __assign = (undefined && undefined.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __spreadArrays = (undefined && undefined.__spreadArrays) || function () { for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; return r; }; function noop() { } function toString(value) { return Object.prototype.toString.call(value); } function getType(value) { var str = toString(value); return /^\[object (.+)\]$/i.exec(str)[1]; } function isNull(value) { return value === undefined || value === null; } function isFunction(value) { if (isNull(value)) return false; return typeof value === "function"; } function isAsyncFunction(value) { if (isNull(value)) return false; return getType(value) === "AsyncFunction"; } function isGeneratorFunction(value) { if (isNull(value)) return false; return getType(value) === "GeneratorFunction"; } function isString(value) { if (isNull(value)) return false; return getType(value) === "String"; } function isNumber(value) { if (isNull(value)) return false; return getType(value) === "Number"; } function isBoolean(value) { if (isNull(value)) return false; return getType(value) === "Boolean"; } function isElement(value) { if (isNull(value)) return false; if (typeof Element !== "undefined") { return value instanceof Element; } else { return (value.tagName && value.nodeType && value.nodeName && value.attributes && value.ownerDocument); } } function isText(value) { if (isNull(value)) return false; return value instanceof Text; } function isObject(value) { if (isNull(value)) return false; var type = getType(value); return type === "Object" || type === "Array"; } function isArray(value) { if (isNull(value)) return false; var v1 = getType(value) === "Array"; var v2 = value instanceof Array; var v3 = !isString(value) && isNumber(value.length) && isFunction(value.splice); var v4 = !isString(value) && isNumber(value.length) && value[0]; return v1 || v2 || v3 || v4; } function isTypedArray(value) { return ArrayBuffer.isView(value) && !(value instanceof DataView); } function isDate(value) { if (isNull(value)) return false; return value instanceof Date; } function isRegExp(value) { return value instanceof RegExp; } function toArray(array) { if (isNull(array)) return []; return Array.prototype.slice.call(array); } function toDate(value) { if (isNumber(value)) { return new Date(value); } else if (isDate(value)) { return value; } else if (isString(value)) { return new Date(replace(replace(value, "-", "/"), "T", " ")); } else { return null; } } function replace(str, from, to) { if (isNull(str)) return str; return str.replace(new RegExp(from, "g"), to); } function formatDate(value, format, options) { if (isNull(format) || isNull(value)) return String(value); var _a = __assign({}, options), _b = _a.utc, utc = _b === void 0 ? false : _b, _c = _a.translate, translate = _c === void 0 ? {} : _c; var dt = toDate(value); var placeholder = { "M+": (utc ? dt.getUTCMonth() : dt.getMonth()) + 1, "d+": utc ? dt.getUTCDate() : dt.getDate(), "h+": utc ? dt.getUTCHours() : dt.getHours(), "m+": utc ? dt.getUTCMinutes() : dt.getMinutes(), "s+": utc ? dt.getUTCSeconds() : dt.getSeconds(), "w+": utc ? dt.getUTCDay() : dt.getDay(), "q+": Math.floor(((utc ? dt.getUTCMonth() : dt.getMonth()) + 3) / 3), "S": utc ? dt.getUTCMilliseconds() : dt.getMilliseconds() }; if (/(y+)/.test(format)) { format = format.replace(RegExp.$1, (dt.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var key in placeholder) { if (new RegExp("(" + key + ")").test(format)) { var value_1 = placeholder[key]; value_1 = translate[value_1] || value_1; format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? value_1 : ("00" + value_1).substr(("" + value_1).length)); } } return format; } function each(list, handler, scope) { if (isNull(list) || isNull(handler)) return; if (isArray(list)) { var listLength = list.length; for (var i = 0; i < listLength; i++) { var rs = handler.call(scope || list[i], i, list[i]); if (!isNull(rs)) return rs; } } else { for (var key in list) { var rs = handler.call(scope || list[key], key, list[key]); if (!isNull(rs)) return rs; } } } function copy(src, dst, ignores) { dst = dst || (isArray(src) ? [] : {}); Object.keys(src).forEach(function (key) { if (ignores && ignores.indexOf(key) > -1) return; delete dst[key]; if (Object.getOwnPropertyDescriptor) { try { Object.defineProperty(dst, key, Object.getOwnPropertyDescriptor(src, key)); } catch (ex) { dst[key] = src[key]; } } else { dst[key] = src[key]; } }); return dst; } function clone(src, ignores) { if (isNull(src) || isString(src) || isNumber(src) || isBoolean(src) || isDate(src)) { return src; } if (isTypedArray(src)) { return src.slice(); } var objClone; try { objClone = new src.constructor(); } catch (_a) { objClone = {}; } ignores = ignores || []; Object.keys(src).forEach(function (key) { var value = src[key]; if (objClone[key] !== value && !ignores.includes(key)) { if (isObject(value)) { objClone[key] = clone(value, ignores); } else { objClone[key] = value; } } }); ["toString", "valueOf"].forEach(function (key) { if (ignores.includes(key)) return; final(objClone, key, src[key]); }); return objClone; } function getPrototypeOf(obj) { return Object.getPrototypeOf(obj); } function setPrototypeOf(obj, proto) { return Object.setPrototypeOf(obj, proto); } function create(proto) { return Object.create(proto); } function mix(dst, src, ignores, mode, ignoreNull) { ignores = ignores || []; if (mode) { switch (mode) { case 1: return mix(dst.prototype, src.prototype, ignores, 0); case 2: mix(dst.prototype, src.prototype, ignores, 0); break; case 3: return mix(dst, src.prototype, ignores, 0); case 4: return mix(dst.prototype, src, ignores, 0); } } src = src || {}; dst = dst || (isArray(src) ? [] : {}); Object.keys(src).forEach(function (key) { if (ignores.includes(key)) return; if (ignoreNull && isNull(src[key])) return; if (isObject(src[key]) && (src[key].constructor === Object || src[key].constructor === Array || src[key].constructor === null)) { dst[key] = mix(dst[key], src[key], ignores, 0, ignoreNull); } else { dst[key] = src[key]; } }); return dst; } function final(obj, name, value) { if (arguments.length === 0) throw new Error("Parameter missing"); if (arguments.length === 1) { return Object.keys(obj).forEach(function (name) { var value = obj[name]; final(obj, name, value); }); } if (arguments.length === 2) return final(obj, name, obj[name]); try { Object.defineProperty(obj, name, { get: function () { return value; }, set: function () { throw new Error("Cannot assign to final property:" + name); }, enumerable: false, configurable: false }); } catch (err) { obj[name] = value; } } function deepEqual(a, b) { if (a === b) return true; if (!isObject(a) || !isObject(b)) return false; var aKeys = Object.keys(a); var bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) return false; var allKeys = aKeys.concat(bKeys); return !allKeys.some(function (key) { return !deepEqual(a[key], b[key]); }); } function fromTo(from, to, handler, step) { if (step === void 0) { step = 1; } step = Math.abs(step || 1); if (from < to) { for (var i = from; i <= to; i += step) handler(i); } else { for (var i = from; i >= to; i -= step) handler(i); } } function newGuid() { var s4 = function () { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); }; return (s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4()); } function setByPath(obj, path, value) { if (isNull(obj) || isNull(path) || path === "") { return; } if (!isArray(path)) { path = path .replace(/\[/, ".") .replace(/\]/, ".") .split("."); } path.forEach(function (name, index) { if (isNull(name) || name.length < 1) return; if (index === path.length - 1) { obj[name] = value; } else { obj[name] = obj[name] || {}; obj = obj[name]; } }); } function getByPath(obj, path, filter) { if (isNull(obj) || isNull(path) || path === "") return obj; if (!isArray(path)) { path = path .replace(/\[/, ".") .replace(/\]/, ".") .split("."); } path.forEach(function (name) { if (isNull(obj) || isNull(name) || name.length < 1) return; obj = filter ? filter(obj[name], name, obj) : obj[name]; }); return obj; } function getFunctionArgumentNames(fn) { if (!fn) return []; var src = fn.toString(); var parts = src .split(")")[0] .split("=>")[0] .split("("); return (parts[1] || parts[0]) .split(",") .map(function (name) { return (name || "").trim(); }) .filter(function (name) { return name !== "function"; }); } var FUNC_REGEXP = /^function\s*\(([\s\S]*?)\)\s*\{([\s\S]*?)\}$/i; function isFunctionString(str) { return FUNC_REGEXP.test(str); } function toFunction(str) { var info = FUNC_REGEXP.exec(str); if (!info || info.length < 3) return; var params = info[1] .split(",") .filter(function (p) { return !!p; }) .map(function (p) { return p.trim(); }); var body = info[2]; return new (Function.bind.apply(Function, __spreadArrays([void 0], params, [body])))(); } function short(str, maxLength) { if (!str) return str; maxLength = maxLength || 40; var strLength = str.length; var trimLength = maxLength / 2; return strLength > maxLength ? str.substr(0, trimLength) + "..." + str.substr(strLength - trimLength) : str; } function firstUpper(str) { if (!isString(str)) return ""; return str.substring(0, 1).toUpperCase() + str.substring(1); } function escapeRegExp(str) { if (!isString(str)) return ""; return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); } function toCamelCase(str, mode) { if (!isString(str)) return ""; if (str) { str = str.replace(/\-[a-z0-9]/g, function ($1) { return $1.slice(1).toUpperCase(); }); str = str.replace(/^[a-z]/i, function ($1) { return mode ? $1.toUpperCase() : $1.toLowerCase(); }); } return str; } function toSplitCase(str) { if (!isString(str)) return ""; if (str) { str = str.replace(/([A-Z])/g, "-$1"); if (str[0] === "-") str = str.slice(1); } return str.toLowerCase(); } function filterHTML(html) { if (!html) return ""; var tagRegExp = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi; return html.replace(tagRegExp, "<$1></$2>"); } function parseHTML(str) { str = str || " "; var parent = document.createElement("div"); parent.innerHTML = filterHTML(str); var childNodes = toArray(parent.childNodes); childNodes.forEach(function (childNode) { return parent.removeChild(childNode); }); return childNodes; } exports.FUNC_REGEXP = FUNC_REGEXP; exports.clone = clone; exports.copy = copy; exports.create = create; exports.deepEqual = deepEqual; exports.each = each; exports.escapeRegExp = escapeRegExp; exports.filterHTML = filterHTML; exports.final = final; exports.firstUpper = firstUpper; exports.formatDate = formatDate; exports.fromTo = fromTo; exports.getByPath = getByPath; exports.getFunctionArgumentNames = getFunctionArgumentNames; exports.getPrototypeOf = getPrototypeOf; exports.getType = getType; exports.isArray = isArray; exports.isAsyncFunction = isAsyncFunction; exports.isBoolean = isBoolean; exports.isDate = isDate; exports.isElement = isElement; exports.isFunction = isFunction; exports.isFunctionString = isFunctionString; exports.isGeneratorFunction = isGeneratorFunction; exports.isNull = isNull; exports.isNumber = isNumber; exports.isObject = isObject; exports.isRegExp = isRegExp; exports.isString = isString; exports.isText = isText; exports.isTypedArray = isTypedArray; exports.mix = mix; exports.newGuid = newGuid; exports.noop = noop; exports.parseHTML = parseHTML; exports.replace = replace; exports.setByPath = setByPath; exports.setPrototypeOf = setPrototypeOf; exports.short = short; exports.toArray = toArray; exports.toCamelCase = toCamelCase; exports.toDate = toDate; exports.toFunction = toFunction; exports.toSplitCase = toSplitCase; exports.toString = toString; Object.defineProperty(exports, '__esModule', { value: true }); return exports; }({}));