UNPKG

luxi-record-utils

Version:
604 lines (585 loc) 22.3 kB
'use strict'; var ConcurrencyControl = /** @class */ (function () { function ConcurrencyControl(taskQueue, maxTaskRunner) { this.taskQueue = []; this.isStoped = true; this.maxTaskRunner = 0; this.tasksResult = []; this.taskRunning = 0; this.taskRunningIndex = 0; var runner = maxTaskRunner; if (!taskQueue || !Array.isArray(taskQueue)) { throw new Error('The concurrency control constructor must pass in the concurrency queue parameter'); } if (!maxTaskRunner || !(typeof (maxTaskRunner) === 'number') || maxTaskRunner !== maxTaskRunner || maxTaskRunner === Infinity) { console.warn('The concurrency control number is invalid, The default is one'); runner = 1; } this.taskQueue = taskQueue; this.maxTaskRunner = runner; } ConcurrencyControl.prototype.run = function () { var _this = this; this.isStoped = false; return new Promise(function (resolve, reject) { var runTask = function () { var _loop_1 = function () { var task = _this.taskQueue.shift(); _this.taskRunning++; _this.taskRunningIndex++; var resultIndex = _this.taskRunningIndex - 1; if (task) { var taskResult = task(); if (taskResult instanceof Promise) { taskResult.then(function (res) { _this.tasksResult[resultIndex] = res; _this.taskRunning--; if (!_this.isStoped) { runTask(); } }).catch(function (err) { _this.isStoped = true; reject(err); }); } else { _this.tasksResult[resultIndex] = taskResult; _this.taskRunning--; runTask(); } } }; while (_this.taskRunning < _this.maxTaskRunner && _this.taskQueue.length && !_this.isStoped) { _loop_1(); } if (_this.taskRunning === 0 && _this.taskQueue.length === 0) { resolve(_this.tasksResult); } }; runTask(); }); }; ConcurrencyControl.prototype.stop = function () { this.isStoped = true; }; Object.defineProperty(ConcurrencyControl.prototype, "result", { get: function () { return this.tasksResult; }, enumerable: false, configurable: true }); return ConcurrencyControl; }()); /* ** 简易版并发控制类 ** @params task任务队列,每个任务返回promise ** @params limit为最大并发数量 */ function asyncTasks(task, limit) { if (limit === void 0) { limit = 1; } if (!task || !Array.isArray(task)) { throw new Error('Requires asynchronous queues'); } var index = 0, resulet = []; var queue = Array(limit).fill(null); queue = queue.map(function () { return new Promise(function (resolve, reject) { var runTask = function () { if (index >= task.length) { resolve(''); return; } var taskItem = task[index]; var resuletIdnex = index; index++; var promise = taskItem(); if (promise instanceof Promise) { promise.then(function (res) { resulet[resuletIdnex] = res; runTask(); }).catch(function (err) { reject(err); }); } else { resulet[resuletIdnex] = promise; runTask(); } }; runTask(); }); }); return Promise.all(queue).then(function () { return resulet; }); } /* ** cookie操作 */ function setCookie(key, value, d) { if (!document) throw new Error('Only applicable to browser environments'); if (!key || !value) throw new Error('Please enter cookie key and value'); var cookie = "".concat(key, "=").concat(value, ";"); if (d !== undefined) { var date = new Date(), expiresDate = date.getDate() + d; date.setDate(expiresDate); cookie = cookie + "expires=".concat(date.toUTCString(), ";"); } document.cookie = cookie; } function getCookie(key) { if (!document) throw new Error('Only applicable to browser environments'); if (!key) throw new Error('Please enter cookie key'); if (!document.cookie) return null; var cookie = document.cookie, array = cookie.split(';'); var value = null; for (var i = 0; i < array.length; i++) { if (array[i].trim().split('=')[0] === key) { value = array[i].trim().split('=')[1]; break; } } return value; } function removeCookie(key) { setCookie(key, '', -1); } /* ** copy复制 ** @params val复制的文本 ** @return 复制成功与否 */ function copy(val) { if (!val || typeof (val) !== 'string') throw new Error('Please enter the copy text content'); var copySuccess = false; var input = document.createElement('input'); input.value = val; document.body.appendChild(input); input.select(); // 选择复制内容 if (document.execCommand) { copySuccess = document.execCommand('copy'); // 执行复制命令 } else { navigator.clipboard.writeText(input.value); copySuccess = true; } document.body.removeChild(input); return copySuccess; } var typeRegList = [ { type: 'year', formatReg: /^Y{4}|Y{2}/g, regionReg: /^year$|^Y$/ }, { type: 'month', formatReg: /M{2}/g, regionReg: /^month$|^M$/ }, { type: 'day', formatReg: /D{2}/g, regionReg: /^day$|^D$|^d$/ }, { type: 'hours', formatReg: /H{2}|h{2}/g, regionReg: /^hours$|^h$/ }, { type: 'minutes', formatReg: /m{2}/g, regionReg: /^minutes$|^m$/ }, { type: 'seconds', formatReg: /s{2}/g, regionReg: /^seconds$|^s$/ }, ]; var DateTime = /** @class */ (function () { function DateTime(value) { var time = value ? new Date(value) : new Date(); if (time.toString() === 'Invalid Date') throw new Error('Please enter a valid time string or timestamp'); this.time = time; } DateTime.prototype.getRegion = function (val, region, type) { var now = this.time.getTime(), value = Number(val); if (Number.isNaN(value)) return; var fullTimeMillisecond = { year: 365 * 24 * 60 * 60 * 1000, month: 30 * 24 * 60 * 60 * 1000, day: 24 * 60 * 60 * 1000, hours: 60 * 60 * 1000, minutes: 60 * 1000, seconds: 1000 }; var resuletMillisecond = 0; typeRegList.forEach(function (_a) { var type = _a.type, regionReg = _a.regionReg; if (regionReg.test(region)) { resuletMillisecond = value * fullTimeMillisecond[type]; } }); return type === 'add' ? new Date(now + resuletMillisecond) : new Date(now - resuletMillisecond); }; DateTime.prototype.format = function (type) { var fullTime = { year: this.time.getFullYear(), month: this.time.getMonth() + 1 >= 10 ? this.time.getMonth() + 1 : "0".concat(this.time.getMonth() + 1), day: this.time.getDate() >= 10 ? this.time.getDate() : "0".concat(this.time.getDate()), hours: this.time.getHours() >= 10 ? this.time.getHours() : "0".concat(this.time.getHours()), minutes: this.time.getMinutes() >= 10 ? this.time.getMinutes() : "0".concat(this.time.getMinutes()), seconds: this.time.getSeconds() >= 10 ? this.time.getSeconds() : "0".concat(this.time.getSeconds()) }; if (type) { var result_1 = type; typeRegList.forEach(function (_a) { var formatReg = _a.formatReg, type = _a.type; result_1 = result_1.replace(formatReg, fullTime[type]); }); return result_1; } else { return ''; } }; DateTime.prototype.before = function (value, type) { var _a; var time = (_a = this.getRegion(value, type, 'reduce')) === null || _a === void 0 ? void 0 : _a.toString(); return new DateTime(time); }; DateTime.prototype.after = function (value, type) { var _a; var time = (_a = this.getRegion(value, type, 'add')) === null || _a === void 0 ? void 0 : _a.toString(); return new DateTime(time); }; return DateTime; }()); function dateTime(value) { return new DateTime(value); } /* ** 简洁防抖函数 */ function debounce(fn, delay, immediate) { if (delay === void 0) { delay = 300; } if (!fn || typeof (fn) !== 'function') throw new Error('Debounce need a callback'); var timer = null, immediately = immediate || false; return function () { var _this = this; var arg = []; for (var _i = 0; _i < arguments.length; _i++) { arg[_i] = arguments[_i]; } if (immediately) { fn.call(this, arg); immediately = false; } else { if (timer) clearTimeout(timer); timer = setTimeout(function () { fn.call(_this, arg); }, delay); } }; } /* ** 节流函数,时间戳简洁版本 ** 定时器版: ** function throttle(fn, delay) { ** let timer = null ** return function () { ** if(!timer) { ** setTimeout(() => { ** fn() ** timer = null ** }, delay) ** } ** } ** } */ function throttle(fn, delay) { if (delay === void 0) { delay = 300; } if (!fn || typeof (fn) !== 'function') throw new Error('Throttle need a callback'); var prevent = 0; return function () { var arg = []; for (var _i = 0; _i < arguments.length; _i++) { arg[_i] = arguments[_i]; } var now = Date.now(); if (now - prevent >= delay) { fn.call(this, arg); prevent = now; } }; } /* ** 通过a标签实现一般的下载 ** @params source下载地址或者内容 ** @params fileName为文件名 */ function downloadFile(source, fileName) { var verify = ['[object String]', '[object Blob]']; if (!source || !verify.includes(Object.prototype.toString.call(source))) { throw new Error('The function accepts a file download address or file content (blob)'); } if (!fileName) throw new Error('Please enter the download file name'); var href = ''; if (Object.prototype.toString.call(source) === verify[0]) { href = source; } else if (Object.prototype.toString.call(source) === verify[1]) { href = window.URL.createObjectURL(source); } var a = document.createElement('a'); a.href = href; a.download = fileName; a.click(); window.URL.revokeObjectURL(href); } /* ** 简单的深拷贝 ** 基本数据类型,数组,日期,正则,函数 */ var simple = ['number', 'string', 'boolean', 'symbol', 'undefined']; function deepClone(target, map) { if (map === void 0) { map = new WeakMap(); } var source; var type = typeof target; if (simple.includes(type)) { source = target; return source; } if (typeof (target) === 'function') return new Function("return ".concat(target.toString()))(); if (typeof (target) === 'object' && target === null) return null; if (Object.prototype.toString.call(target) === '[object Date]') return new Date(target); if (Object.prototype.toString.call(target) === '[object RegExp]') return new RegExp(target); source = Array.isArray(target) ? [] : {}; if (map.get(target)) { return map.get(target); } map.set(target, source); for (var key in target) { if (target.hasOwnProperty(key)) { if (typeof target[key] === 'object') { source[key] = deepClone(target[key], map); } else { source[key] = target[key]; } } } return source; } function exportXlsOrCsv(title, data, fileName) { if (!title || !Array.isArray(title) || title.length < 1) { throw new Error('The table requires an array of header information'); } if (fileName) { var tableFileSuffix = ['xlsx', 'xls', 'xlsb', 'xlsm', 'csv']; var suffixIndex = fileName.split('.').length - 1, fileSuffix = fileName.split('.')[suffixIndex]; if (!tableFileSuffix.includes(fileSuffix)) { throw new Error("Table files should therefore end with ['xlsx', 'xls', 'xlsb', 'xlsm', 'csv'] suffix"); } } var result = [], tableTitleKey = [], tableTitleValue = []; title.forEach(function (item) { item.key && tableTitleKey.push(item.key); item.value && tableTitleValue.push(item.value); }); result.push(tableTitleValue.join(',') + '\n'); if (Array.isArray(data) && data.length > 0) { data.forEach(function (item) { var list = {}; tableTitleKey.forEach(function (key) { list[key] = item[key]; }); result.push(Object.values(list).join(',') + '\n'); }); } var blob = new Blob(['\uFEFF' + result.join('')], { type: 'text/plain;charset=utf-8', }); downloadFile(blob, fileName || 'download.xlsx'); } /* ** 超长数字相加 ** 只允许输入字符串,因为数字长度问题会把一些超大数字转化为科学计数法 ** 例如: 0.000000000000003 ==> '3e-15' */ function numberAdd(a, b) { if (!a || !b) throw new Error('Please enter two strings composed of numbers'); var isReduce = (Number(a) > 0 && Number(b) < 0 || Number(a) < 0 && Number(b) > 0) ? true : false; var isNegative = Number(a) < 0 && Number(b) < 0 ? true : false; var resulet = '', carry = 0; if (isReduce) { var numberOne = Number(a), numberTwo = Number(b); var absNumberOne = a.replace('-', ''), absNumberTwo = b.replace('-', ''); var hasMinusSign = (Math.abs(numberOne) > Math.abs(numberTwo) && numberOne < 0) || (Math.abs(numberTwo) > Math.abs(numberOne) && numberTwo < 0) ? true : false; var length_1 = absNumberOne.length; var big = Math.abs(numberOne) > Math.abs(numberTwo) ? absNumberOne : absNumberTwo; var small = Math.abs(numberOne) < Math.abs(numberTwo) ? absNumberOne : absNumberTwo; for (var i = length_1 - 1; i >= 0; i--) { var numberA = Number(big[i]), numberB = Number(small[i]); var tmp = numberA - numberB - carry; if (tmp < 0) { carry = 1; resulet = tmp + 10 + resulet; } else { carry = 0; resulet = tmp + resulet; } } resulet = hasMinusSign ? "-".concat(resulet) : resulet; } else { var stringOne = isNegative ? a.replace('-', '') : a; var stringTwo = isNegative ? b.replace('-', '') : b; var length_2 = stringOne.length; for (var i = length_2 - 1; i >= 0; i--) { var numberA = Number(stringOne[i]), numberB = Number(stringTwo[i]); var tmp = numberA + numberB + carry; carry = Math.floor(tmp / 10); resulet = tmp % 10 + resulet; } if (carry) resulet = carry + resulet; resulet = isNegative ? "-".concat(resulet) : resulet; } return resulet; } function largeNumberAdd(num1, num2) { var stringOne = String(num1), stringTwo = String(num2); var reg = /^(-?\d+)(\.\d+)?$/; // /^-?\d+$/ 整数 /^0+$/ 全零 if (!reg.test(stringOne) || !reg.test(stringTwo)) { throw new Error('Please enter a string composed of numbers'); } var stringOneLess = Number(stringOne) < 0 ? true : false; var stringTwoLess = Number(stringTwo) < 0 ? true : false; var isFloat = stringOne.includes('.') || stringTwo.includes('.'); var pointIndex = null; if (isFloat) { var stringOneFloat = stringOne.split('.')[1] || ''; var stringTwoFloat = stringTwo.split('.')[1] || ''; pointIndex = Math.max(stringOneFloat.length, stringTwoFloat.length); stringOneFloat = stringOneFloat.padEnd(pointIndex, '0'); stringTwoFloat = stringTwoFloat.padEnd(pointIndex, '0'); pointIndex = Number("-".concat(pointIndex)); var stringOneInteger = stringOne.replace('-', '').split('.')[0]; var stringTwoInteger = stringTwo.replace('-', '').split('.')[0]; var maxLength = Math.max(stringOneInteger.length, stringTwoInteger.length); stringOneInteger = stringOneInteger.padStart(maxLength, '0'); stringTwoInteger = stringTwoInteger.padStart(maxLength, '0'); stringOne = stringOneLess ? "-".concat(stringOneInteger).concat(stringOneFloat) : stringOneInteger + stringOneFloat; stringTwo = stringTwoLess ? "-".concat(stringTwoInteger).concat(stringTwoFloat) : stringTwoInteger + stringTwoFloat; } else { var stringOneInteger = stringOne.replace('-', ''); var stringTwoInteger = stringTwo.replace('-', ''); var maxLength = Math.max(stringOneInteger.length, stringTwoInteger.length); stringOneInteger = stringOneInteger.padStart(maxLength, '0'); stringTwoInteger = stringTwoInteger.padStart(maxLength, '0'); stringOne = stringOneLess ? "-".concat(stringOneInteger) : stringOneInteger; stringTwo = stringTwoLess ? "-".concat(stringTwoInteger) : stringTwoInteger; } console.log(stringOne, stringTwo); var result = numberAdd(stringOne, stringTwo); if (pointIndex) return "".concat(result.slice(0, pointIndex), ".").concat(result.slice(pointIndex)); return result; } /****************************************************************************** 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. ***************************************************************************** */ /* global Reflect, Promise */ 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 searchPathFromTree(tree, key, value, childKey) { if (childKey === void 0) { childKey = 'child'; } var path = []; var resulet = []; path.push(tree[key]); if (tree[key] === value) return path; var child = tree[childKey]; var traverse = function (data, path, key, value, childKey) { if (childKey === void 0) { childKey = 'child'; } if (!data.length) return; for (var _i = 0, data_1 = data; _i < data_1.length; _i++) { var tree_1 = data_1[_i]; path.push(tree_1[key]); if (tree_1[key] === value) { resulet = __spreadArray([], path, true); break; } var child_1 = Array.isArray(tree_1[childKey]) ? tree_1[childKey] : []; traverse(child_1, path, key, value, childKey); // 遍历 path.pop(); // 回溯 } }; traverse(child, path, key, value, childKey); return resulet; } /* ** 扁平化一棵树 function treeToArray(tree: any[]) { let res = [] for (const item of tree) { const { children, ...i } = item if (children && children.length) { res = res.concat(treeToArray(children)) } res.push(i) } return res } */ function serchParams(k) { if (!window) throw new Error('This function just use in browser environment'); var result = {}; var string = window.location.search.slice(1); if (!string) return {}; var list = string.split('&'); for (var i = 0; i < list.length; i++) { var arr = list[i].split('='); if (k && arr[0] === k) { return arr[1] || ''; } result[arr[0]] = arr[1] || ''; } return result; } exports.ConcurrencyControl = ConcurrencyControl; exports.asyncTasks = asyncTasks; exports.copy = copy; exports.dateTime = dateTime; exports.debounce = debounce; exports.deepClone = deepClone; exports.downloadFile = downloadFile; exports.exportXlsOrCsv = exportXlsOrCsv; exports.getCookie = getCookie; exports.largeNumberAdd = largeNumberAdd; exports.removeCookie = removeCookie; exports.searchPathFromTree = searchPathFromTree; exports.serchParams = serchParams; exports.setCookie = setCookie; exports.throttle = throttle;