UNPKG

js-xxx

Version:

前端 JavaScript 常用函数/工具/方法库

1,482 lines (1,400 loc) 967 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.$xxx = {})); })(this, (function (exports) { 'use strict'; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(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); }; function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __values(o) { var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; if (m) return m.call(o); if (o && typeof o.length === "number") return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spreadArray(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; /* eslint-disable */ var prettierRules = function (rules) { if (rules === void 0) { rules = {}; } return (__assign({ printWidth: 120, proseWrap: 'never', semi: true, singleQuote: true, jsxSingleQuote: false, bracketSpacing: true, bracketSameLine: false, arrowParens: 'always', insertPragma: false, tabWidth: 2, useTabs: false, endOfLine: 'lf', trailingComma: 'all', htmlWhitespaceSensitivity: 'ignore', // 每个文件格式化的范围是文件的全部内容 rangeStart: 0, rangeEnd: Infinity, quoteProps: 'as-needed' }, (rules !== null && rules !== void 0 ? rules : {}))); }; var eslintRules = function (skipWords, rules) { if (skipWords === void 0) { skipWords = []; } if (rules === void 0) { rules = {}; } return (__assign({ 'zob/comment': 'error', '@typescript-eslint/ban-ts-comment': 'off', 'no-useless-escape': 'warn', 'prettier/prettier': [ 'error', { // trailingComma: 'all', // arrowParens: 'always', // htmlWhitespaceSensitivity: 'ignore', }, { usePrettierrc: true }, ], 'no-undef': ['error'], 'spaced-comment': ['error', 'always'], 'space-before-blocks': ['error', 'always'], 'no-multiple-empty-lines': ['error', { max: 5 }], 'no-mixed-spaces-and-tabs': ['error', false], 'comma-dangle': ['error', 'only-multiline'], indent: ['error', 2, { SwitchCase: 1 }], 'linebreak-style': ['error', 'unix'], quotes: ['error', 'single'], semi: ['error', 'always'], // 'no-unused-vars': ['warn', { vars: 'all', args: 'after-used', ignoreRestSiblings: true }], // @typescript-eslint/no-unused-vars '@typescript-eslint/no-explicit-any': ['off'], 'no-irregular-whitespace': [ 'error', { skipStrings: true, skipComments: true, skipRegExps: true, skipTemplates: true }, ], 'no-multi-spaces': ['error', { ignoreEOLComments: true }], 'no-trailing-spaces': ['error', { skipBlankLines: false }], 'brace-style': ['error', '1tbs', { allowSingleLine: false }], 'key-spacing': ['warn', { beforeColon: false, afterColon: true }], 'object-curly-spacing': ['error', 'always'], 'array-bracket-spacing': ['error', 'never'], 'max-lines': ['error', 800], 'max-statements': ['error', 100], 'spellcheck/spell-checker': [ // 拼写检查警告 'warn', { comments: false, strings: true, identifiers: true, lang: 'en_US', skipWords: __spreadArray([ // npm i modules-words // 常用词库 'javascript', 'debounce', 'pathname', 'minify', 'charset', 'unmount', 'poweroff', 'resize', 'linux', 'darwin', 'resizable', 'renderer', 'biugle', 'unordered', 'dropdown', 'checkbox', 'tooltip', 'namespaced', 'echarts', 'onopen', 'formatter', 'xlocation', 'xcall', 'utils', 'cordova', 'ionics', 'lodash', 'dayjs', 'splashscreen', 'uglify', 'jsonp', 'async', 'bcrypt', 'werbs', 'navbar', 'popover', 'substr', 'zindex', 'viewport', 'validator', 'webserver', 'whitelist', 'runtime', 'proto', 'popup', 'polyfill', 'preload', 'mixin', 'middleware', 'lifecycle', 'linter', 'hostname', 'dirname', 'autocomplete', 'sourcemap', 'dicts', 'undef', 'asyncfunction', 'xxxxx', 'keydown', 'keyup', 'keypress', 'webkit', 'uint8', 'radix', 'storage', 'favicon', 'compat', 'keyframes', 'padlen', 'tring', 'xhtml', 'xmind', 'decrypt', 'decrypted', 'multipart', 'contextmenu', 'loadend', 'callee', 'slugify', 'ciphertext', 'urlencoded', 'cancelable', 'ascii', 'unicode', 'rollup', 'axios', 'redux', 'unlink', 'macos', 'submenu', 'nodemon', 'hhiiss', 'hhmmss', 'hhmmdd', 'whitesmoke', 'esbuild', 'commonjs', 'preset', 'presets', 'browsers', 'iframe', 'contenttype', 'immer', 'ahooks', 'devtool', 'devtools', 'register', 'unregister', 'maximize', 'unmaximize', 'unminimize', 'minimize', 'localhost', 'uninstall', 'unhandled', 'unhandledrejection' ], __read((skipWords !== null && skipWords !== void 0 ? skipWords : [])), false), skipIfMatch: [ // http url 'http://[^s]*', // Auxiliary werbs // see: https://github.com/aotaduy/eslint-plugin-spellcheck/issues/7 // eslint-disable-next-line quotes "(\\s|^)\\w+'t(\\s|$)", // ordinals // https://github.com/aotaduy/eslint-plugin-spellcheck/issues/8 '(\\s|^|\\w+)\\d+(st|nd|rd|th)(\\s|[A-Z][a-zA-Z]+|$)', // pre/post prefixes both in kebab case and camel case '(\\s|^)(pre|post)([-\\w]|[A-Z])[a-zA-Z]+(\\s|$)', // xml tags '<(?:/)?[\\w-]+>', // cryptographic octal hashes '^[0-9a-f]{5,999}$', // hex colors '^#[0-9a-f]{3,6}$', // For MIME Types '^[-\\w]+/[-\\w\\.]+$', ], skipWordIfMatch: [ '^foobar.*$', // words that begin with foobar will not be checked ], minLength: 5, // >=5 个字符以上才监测 }, ], 'import/first': ['error'], 'import/exports-last': ['error'], 'import/newline-after-import': ['error'], 'import/no-duplicates': ['error'], 'import/order': ['error', { 'newlines-between': 'never' }] }, (rules !== null && rules !== void 0 ? rules : {}))); }; var sortJSON = function (obj) { // 去重并获取对象的键数组 var keys = Object.keys(obj); // 按键的首字符进行排序 var sortedKeys = keys.sort(function (a, b) { var aKey = a[0]; var bKey = b[0]; return aKey.localeCompare(bKey); }); // 构建分类和排序后的对象 var sortedAndGroupedObject = sortedKeys.reduce(function (result, key) { var firstChar = key[0]; if (!result[firstChar]) { result[firstChar] = []; } result[firstChar].push(key); return result; }, {}); // 在每个分类中按键的长度进行排序 for (var group in sortedAndGroupedObject) { sortedAndGroupedObject[group].sort(function (a, b) { return a.length - b.length; }); } // 拼接分类后的键数组 var finalKeys = Object.values(sortedAndGroupedObject).flat(); // 构建排序后的对象 var sortedObject = finalKeys.reduce(function (result, key) { result[key] = obj[key]; return result; }, {}); // 转换为 JSON 字符串并输出 var jsonString = JSON.stringify(sortedObject); return jsonString; }; /* * @Author: HxB * @Date: 2022-04-26 14:10:35 * @LastEditors: DoubleAm * @LastEditTime: 2024-09-21 13:41:27 * @Description: 类型校验等函数 * @FilePath: \js-xxx\src\Types\index.ts */ /** * 获取变量类型 * @example * getType(1); /// 'number' * getType(async function(){}); /// 'asyncfunction' * @param variable 变量 * @returns * @category Types-类型相关 */ function getType(variable) { return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase(); } /** * 任意值转换为字符串 * @example * toStr({}); /// '{}' * toStr([1, 2]); /// '[1,2]' * toStr(null); /// '' * @param value 值 * @returns * @category Types-类型相关 */ function toStr(value) { if (value == null) { return ''; } if (typeof value == 'object') { return JSON.stringify(value); } return value.toString(); } /** * 任意值转换为数字 * @example * toNum({}); /// 0 * toNum([2]); /// 2 * toNum('-123'); /// -123 * @param value 值 * @returns * @category Types-类型相关 */ function toNum(value) { value = Number(value); return isNaN$1(value) ? 0 : value; } /** * 任意值转换为布尔类型 * @example * toBool(0); /// true * toBool(''); /// true * toBool('', [0, '']); /// false * toBool(0, [0, '']); /// false * toBool('0'); /// true * toBool(1); /// true * toBool('false'); /// false * toBool('null'); /// false * toBool('undefined'); /// false * toBool('NaN'); /// false * toBool(null); /// false * @param value 值 * @param falseList 判断为 false 的值列表 * @returns * @category Types-类型相关 */ function toBool(value, falseList) { if (falseList === void 0) { falseList = []; } if (__spreadArray(['false', 'null', 'undefined', 'NaN'], __read(falseList), false).includes(value)) { return false; } if (value === '') { return true; } if (value === 0) { return true; } return !!value; } /** * 检查字符串是否为有效的 JSON * @example * isJSON('{"name":"leo", "age":20}'); /// true * isJSON('{"name":"leo", age:"20"}'); /// false * isJSON(null); /// true * @param str 字符串 * @returns * @category Types-类型相关 */ function isJSON(str) { try { JSON.parse(str); return true; } catch (e) { return false; } } /** * 检查是否为 boolean 类型 * @example * isBool(true); /// true * isBool(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isBool(value) { return getType(value) === 'boolean'; } /** * 检查是否 date 类型 * @example * isDate(new Date()); /// true * isDate(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isDate(value) { return getType(value) === 'date'; } /** * 检查是否 Invalid Date 类型 * @example * isInvalidDate(new Date()); /// false * isInvalidDate(null); /// false * isInvalidDate(undefined); /// true * isInvalidDate(new Date('invalid date')); /// true * @param date 值 * @returns * @category Types-类型相关 */ function isInvalidDate(date) { return isNaN$1(new Date(date).getTime()); } /** * 检查是否字符串类型 * @example * isStr('test'); /// true * isStr(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isStr(value) { return getType(value) === 'string'; } /** * 检查是否 undefined * 该函数使用 `void 0` 来判断是否为 `undefined`,而不是直接与全局的 `undefined` 变量比较。 * 使用 `void 0` 的好处是,即使全局的 `undefined` 变量被重新赋值,`void 0` 依然保证返回真正的 undefined 。 * @example * isUndef(undefined); /// true * isUndef(null); /// false * isUndef(void 0); /// true * @param value 值 * @returns * @category Types-类型相关 */ function isUndef(value) { return value === void 0; // return getType(value) === 'undefined'; } /** * 检查是否 null * @example * isNull(undefined); /// false * isNull(null); /// true * @param value 值 * @returns * @category Types-类型相关 */ function isNull(value) { return getType(value) === 'null'; } /** * 检查是否 number 类型 * @example * isNum(NaN); /// false * isNum(1); /// true * @param value 值 * @returns * @category Types-类型相关 */ function isNum(value) { return getType(value) === 'number' && !Object.is(NaN, value); } /** * 检查是否数组 * @example * isArr([]); /// true * isArr({}); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isArr(value) { return Array.isArray(value); } /** * 检查是否对象 * @example * isObj({}); /// true * isObj(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isObj(value) { return getType(value) === 'object'; } /** * 检查是否为 dom 元素 * @example * isElement(document.body); /// true * isElement(document); /// false * isElement({}); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isElement(value) { return !!(value && value.nodeType === 1); } /** * 检查是否为 function * @example * isFn(function(){}); /// true * isFn(async function(){}); /// true * isFn(new Promise((resolve, reject) => resolve()); /// false * isFn({}); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isFn(value) { var type = getType(value); return type === 'function' || type === 'generatorfunction' || type === 'asyncfunction'; } /** * 检查是否为 Promise * @example * isPromise(function(){}); /// false * isPromise(async function(){}); /// false * isPromise(new Promise((resolve, reject) => resolve())); /// true * @param value 值 * @returns * @category Types-类型相关 */ function isPromise(value) { return getType(value) === 'promise' || (isFn(value === null || value === void 0 ? void 0 : value.then) && isFn(value === null || value === void 0 ? void 0 : value.catch)); } /** * 检查是否为 NaN * @example * isNaN(1); /// false * isNaN(NaN); /// true * @param value 值 * @returns * @category Types-类型相关 */ function isNaN$1(value) { return Object.is(NaN, value); } /** * 检查是否为 Blob * @example * isBlob(new Blob()); /// true * isBlob(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isBlob(value) { return getType(value) === 'blob'; } /** * 检查是否为 ArrayBuffer * @example * isArrayBuffer(new ArrayBuffer()); /// true * isArrayBuffer(null); /// false * @param value 值 * @returns * @category Types-类型相关 */ function isArrayBuffer(value) { return getType(value) === 'arraybuffer'; } /* * @Author: HxB * @Date: 2022-04-26 11:52:01 * @LastEditors: DoubleAm * @LastEditTime: 2025-07-07 11:47:39 * @Description: 数组常用函数 * @FilePath: /js-xxx/src/Array/index.ts */ /** * 数组对象转对象,按照指定的 key 分组。 * @example * data2Obj([{a: 1, b: 2}, {a: 3}, {b: 1}, {c: 1}], 'a'); /// {1: {a: 1, b: 2}, 3: {a: 3}, undefined: {c: 1}} * data2Obj([{a: 1, b: 'b1'}, {a: 3}, {a: 2, b: 'b2'}], 'a', 'b'); /// { '1': 'b1', '2': 'b2', '3': undefined } * @param sourceData 源数据 * @param key 分组的 key * @param vKey 值的 key,默认为整个值。 * @returns * @category Array-数组相关 */ function data2Obj(sourceData, key, vKey) { var obj = {}; if (!Array.isArray(sourceData)) { return obj; } sourceData.forEach(function (item) { obj[item[key]] = vKey ? item[vKey] : item; }); return obj; } /** * 数组对象转数组值 * @example * data2Arr([{a: 1, b: 2}, {a: 3}, {b: 1}], 'a'); /// [1, 3] * @param sourceData 源数据 * @param key 取值的 key * @returns * @category Array-数组相关 */ function data2Arr(sourceData, key) { var _a; var arr = []; if (sourceData.length === 0) { return arr; } for (var k in sourceData) { ((_a = sourceData[k]) === null || _a === void 0 ? void 0 : _a[key]) && arr.push(sourceData[k][key]); } return arr; } /** * 数组对象转换为对象数组,需确保源数据已经去重哦,否则会暴力去重,最后一条数据有效。 * 一般图表类插件需要此类转换 * @example * const data = [{ id: 1, name: '张三', score: 98, remark: '语文成绩' }, { id: 3, name: '王五', score: 98 }, { id: 3, name: '王五', score: 99, remark: '最后一条有效成绩' }, { id: 2, name: '李四', score: 100 }]; * arrObj2objArr(data, 'id'); /// {"id": [1, 2, 3], "name": ["张三", "李四", "王五"], "score": [98, 100, 99], "remark": ["语文成绩", null, "最后一条有效成绩"]} * @param data 源数据 * @param key 用于转换的 key * @returns * @category Array-数组相关 */ function arrObj2objArr(data, key) { var result = {}; try { var keys_1 = []; data.forEach(function (item) { var itemKeys = Object.keys(item); keys_1 = itemKeys.length > keys_1.length ? itemKeys : keys_1; }); unique(data, function (a, b) { return a[key] === b[key]; }) .sort(sortBy(key)) .forEach(function (item) { keys_1.forEach(function (objKey) { var _a; if (!result[objKey]) { result[objKey] = []; } result[objKey].push((_a = item[objKey]) !== null && _a !== void 0 ? _a : null); }); }); } catch (e) { console.log('js-xxx:arrObj2objArrError--->', e); } return result; } /** * 数组去重 * @example * unique([1, 2, 3, 1, 2, 3]); /// [1, 2, 3] * unique([{id: 1, value: 'hello'}, {id: 2, value: 'world'}, {id: 2, value: 'world', others: true}], (a, b) => a.id === b.id); /// [id1, id2 带 true] * @param arr 数组 * @param filter 过滤逻辑 * @returns * @category Array-数组相关 */ function unique(arr, filter) { if (arr.length == 1) { return arr; } if (!filter) { filter = function (a, b) { return a === b; }; } var len = arr.length; return arr.filter(function (item, idx, arr) { while (++idx < len) { if (filter(item, arr[idx])) return false; } // arr.indexOf(item) === idx; return true; }); } /** * 返回排序回调函数(支持中文,不支持一级数据与混合类型。) * @example * sortCallBack('createDt', true); /// 按照 createDt 升序排列 * const arr = [{name: '666'}, {name: '333'}] * arr.sort(sortCallBack('name')); /// [{name: '333'}, {name: '666'}] * arr.sort(sortCallBack('name', false)); /// [{name: '666'}, {name: '333'}] * @param key 排序的字段 * @param isAscend 是否升序 * @returns * @category Array-数组相关 */ function sortCallBack(key, isAscend) { if (isAscend === void 0) { isAscend = true; } return function (a, b) { return (a[key] > b[key] ? (isAscend ? 1 : -1) : isAscend ? -1 : 1); }; } /** * 数组乱序 * @example * arrayShuffle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); /// [5, 9, 1, 10, 2, 6, 4, 8, 3, 7] * @param arr 数组 * @returns * @category Array-数组相关 */ function arrayShuffle(arr) { return arr.sort(function () { return Math.random() - 0.5; }); } /** * 数组排序(支持多条件排序+中文) * @example * arraySort(["a", "3", 1, 2, "b"]); /// [1, 2, '3', 'a', 'b'] * arraySort(["a", "3", 1, 2, "b"], 'asc'); /// [1, 2, '3', 'a', 'b'] * arraySort(["a", "3", 1, 2, "b"], false); /// ['b', 'a', '3', 2, 1] * arraySort(["a", "3", 1, 2, "b"], 'desc'); /// ['b', 'a', '3', 2, 1] * let arr1 = [{ a: 'a', b: 'b', c: '张三', d: 1 }, { a: 'c', b: 'd', c: '李四', d: 2 }, { a: 'e', b: 'f', c: '王五', d: 3 }]; * arraySort(arr1, false, 'a'); /// e - c - a * arraySort(arr1, false, ['d', 'c']); /// 3 - 2 - 1 * arraySort(arr1, 'DESC', ['c']); /// 张三 - 王五 - 李四 * @param arr 数组 * @param type 类型 * @param keys 关键字/集合 * @returns * @category Array-数组相关 */ function arraySort(arr, type, keys) { if (type === void 0) { type = 'asc'; } var isAscend = type == 'asc' || type == 'ASC' || type == true; try { if (!keys) { return arr.sort(function (a, b) { return isAscend ? toStr(a).localeCompare(toStr(b)) : toStr(b).localeCompare(toStr(a)); }); } if (isStr(keys)) { return arr.sort(function (a, b) { var aSort = toStr(a[keys]); var bSort = toStr(b[keys]); return isAscend ? aSort.localeCompare(bSort) : bSort.localeCompare(aSort); }); } return arr.sort(function (a, b) { var _a, _b; var aSort = (_a = keys === null || keys === void 0 ? void 0 : keys.reduce(function (total, currentValue) { return toStr(total).concat(a[currentValue]); }, '')) !== null && _a !== void 0 ? _a : '0'; var bSort = (_b = keys === null || keys === void 0 ? void 0 : keys.reduce(function (total, currentValue) { return toStr(total).concat(b[currentValue]); }, '')) !== null && _b !== void 0 ? _b : '0'; return isAscend ? aSort.localeCompare(bSort) : bSort.localeCompare(aSort); }); } catch (e) { return arr; } } /** * 返回排序回调函数(也支持中文、多个字段、混合类型) * @example * ['a', '3', 1, 2, 'b'].sort(sortBy('', false)); /// ['b', 'a', '3', 2, 1] * ['a', '3', 1, 2, 'b'].sort(sortBy()); /// [1, 2, '3', 'a', 'b'] * sortBy('createDt'); /// 按照 createDt 升序排列 * sortBy(['name', 'age'], false); /// 按照 name + age 降序排列 * @param keys 排序的字段/集合 * @param isAscend 是否升序 * @returns * @category Array-数组相关 */ function sortBy(keys, isAscend) { if (isAscend === void 0) { isAscend = true; } if (!keys) { return function (a, b) { return isAscend ? toStr(a).localeCompare(toStr(b)) : toStr(b).localeCompare(toStr(a)); }; } var transferKeys = isStr(keys) ? [keys] : keys; return function (a, b) { var _a, _b; var aSort = (_a = transferKeys === null || transferKeys === void 0 ? void 0 : transferKeys.reduce(function (total, currentValue) { return toStr(total).concat(a[currentValue]); }, '')) !== null && _a !== void 0 ? _a : '0'; var bSort = (_b = transferKeys === null || transferKeys === void 0 ? void 0 : transferKeys.reduce(function (total, currentValue) { return toStr(total).concat(b[currentValue]); }, '')) !== null && _b !== void 0 ? _b : '0'; return isAscend ? aSort.localeCompare(bSort) : bSort.localeCompare(aSort); }; } /** * 填充数组空值,取前后值得中间数。 * @example * arrayFill([1, undefined, 3, undefined, 4]); /// [1, 2, 3, 3.5, 4] * arrayFill([1, undefined, 3, undefined, 4], 0); ///  [1, 2, 3, 4, 4] * arrayFill([1, undefined, 3, undefined, 10.55], 2); /// [1, 2, 3, 6.78, 10.55] * @param arr 数组 * @param n 保留小数位 * @returns * @category Array-数组相关 */ function arrayFill(arr, n) { var result = []; for (var i = 0; i < arr.length; i++) { if (!arr[i]) { // 寻找前一个非空值的索引 var prevIndex = i - 1; while (!arr[prevIndex]) { prevIndex--; } // 寻找后一个非空值的索引 var nextIndex = i + 1; while (!arr[nextIndex]) { nextIndex++; } // 计算前后两个非空值的中间值 var prevValue = arr[prevIndex]; var nextValue = arr[nextIndex]; var middleValue = (prevValue + nextValue) / 2; result.push(Number(n === undefined ? middleValue : Number(middleValue).toFixed(n))); } else { result.push(arr[i]); } } return result; } /** * 将数组拆分为多个子数组(每组 n 个元素) * @example * const arr = [1, 2, 3, 4, 5, 6, 7]; * console.log(arrayChunk(arr, 3)); ///[ [1, 2, 3], [4, 5, 6], [7] ] * console.log(arrayChunk(arr, 8)); ///[ [1, 2, 3, 4, 5, 6, 7] ] * @param arrayData 原始数组 * @param n 每组元素个数 * @returns * @category Array-数组相关 */ function arrayChunk(arrayData, n) { // 处理边界情况 if (!Array.isArray(arrayData)) return []; if (typeof n !== 'number' || n < 1) return []; var result = []; var len = arrayData.length; // 使用循环切片法 for (var i = 0; i < len; i += n) { result.push(arrayData.slice(i, i + n)); } return result; } /* * @Author: HxB * @Date: 2022-04-26 16:29:18 * @LastEditors: DoubleAm * @LastEditTime: 2024-08-23 10:38:45 * @Description: Cookies 常用函数 * @FilePath: \js-xxx\src\Cookies\index.ts */ /** * Get Cookie * @example * getCookie('name'); /// 获取 name 对应的 Cookie 值 * @param key Cookie key * @returns * @category Storage-存储相关 */ function getCookie(key) { var reg = new RegExp('(^| )' + key + '=([^;]*)(;|$)'); // @ts-ignore var arr = document.cookie.match(reg) ? unescape(document.cookie.match(reg)[2]) : null; return arr; } /** * Set Cookie * @example * setCookie('name', 'value', 1); /// 设置 name 对应的 Cookie 值 * @param key Cookie key * @param value Cookie value * @param expires Cookie expires * @returns * @category Storage-存储相关 */ function setCookie(key, value, expires) { // 没有设置有效期,默认有效期是 30 天。 expires = expires || 30; // 获取当前日期 var exp = new Date(); // 设置过期日期 exp.setTime(exp.getTime() + expires * 24 * 60 * 60 * 1000); document.cookie = key + '=' + escape(value) + ';expires=' + exp.toUTCString() + ';path=/'; } /** * Remove Cookie * @example * removeCookie('name'); /// 删除 name 对应的 Cookie * @param key Cookie key * @returns * @category Storage-存储相关 */ function removeCookie(key) { var exp = new Date(); exp.setTime(exp.getTime() - 1); var cVal = getCookie(key); if (cVal !== null) { document.cookie = key + '=' + cVal + ';expires=' + exp.toUTCString() + ';path=/'; } } /** * Clear Cookie * @example * clearCookies(); /// 删除所有的 Cookie * @returns * @category Storage-存储相关 */ function clearCookies() { document.cookie .split(';') .forEach(function (cookie) { return (document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, "=;expires=".concat(new Date(0).toUTCString(), ";path=/"))); }); } var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function commonjsRequire (path) { throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); } var cryptoJs = {exports: {}}; var core = {exports: {}}; (function (module, exports) { (function (root, factory) { { // CommonJS module.exports = factory(); } }(commonjsGlobal, function () { /*globals window, global, require*/ /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined$1) { var crypto; // Native crypto from window (Browser) if (typeof window !== 'undefined' && window.crypto) { crypto = window.crypto; } // Native crypto in web worker (Browser) if (typeof self !== 'undefined' && self.crypto) { crypto = self.crypto; } // Native crypto from worker if (typeof globalThis !== 'undefined' && globalThis.crypto) { crypto = globalThis.crypto; } // Native (experimental IE 11) crypto from window (Browser) if (!crypto && typeof window !== 'undefined' && window.msCrypto) { crypto = window.msCrypto; } // Native crypto from global (NodeJS) if (!crypto && typeof commonjsGlobal !== 'undefined' && commonjsGlobal.crypto) { crypto = commonjsGlobal.crypto; } // Native crypto import via require (NodeJS) if (!crypto && typeof commonjsRequire === 'function') { try { crypto = require('crypto'); } catch (err) {} } /* * Cryptographically secure pseudorandom number generator * * As Math.random() is cryptographically not safe to use */ var cryptoSecureRandomInt = function () { if (crypto) { // Use getRandomValues method (Browser) if (typeof crypto.getRandomValues === 'function') { try { return crypto.getRandomValues(new Uint32Array(1))[0]; } catch (err) {} } // Use randomBytes method (NodeJS) if (typeof crypto.randomBytes === 'function') { try { return crypto.randomBytes(4).readInt32LE(); } catch (err) {} } } throw new Error('Native crypto module could not be used to get secure random number.'); }; /* * Local polyfill of Object.create */ var create = Object.create || (function () { function F() {} return function (obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }()); /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn var subtype = create(this); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init') || this.init === subtype.init) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined$1) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var j = 0; j < thatSigBytes; j += 4) { thisWords[(thisSigBytes + j) >>> 2] = thatWords[j >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push(cryptoSecureRandomInt()); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Conver