UNPKG

@dimplesyj/util

Version:

[![NPM version](https://img.shields.io/npm/v/@dimplesyj/util?color=a1b858&label=)](https://www.npmjs.com/package/@dimplesyj/util) [![Docs](https://www.paka.dev/badges/v0/cute.svg)](https://www.paka.dev/npm/@dimplesyj/util)

491 lines (472 loc) 16.2 kB
'use strict'; const dayjs = require('dayjs'); const throttleDebounce = require('throttle-debounce'); function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } const dayjs__default = /*#__PURE__*/_interopDefaultCompat(dayjs); const removeAt = (arr, el) => { const i = arr.indexOf(el); if (i > -1) arr.splice(i, 1); }; const insertAt = (arr, index, ...v) => { arr.splice(index + 1, 0, ...v); return arr; }; const last = (arr) => arr && arr.length ? arr[arr.length - 1] : void 0; const lastN = (arr, n) => arr.slice(-n); function all(arr, fn = Boolean) { return arr.every(fn); } function allEqual(arr) { return arr.every((val) => val === arr[0]); } function clone(obj) { return JSON.parse(JSON.stringify(obj)); } function clearNull(obj) { if (typeof obj === "object") { const result = clone(obj); for (const key in result) { const current = result[key]; if ([null, ""].includes(current) || isArray(current) && current.length === 0) delete result[key]; else result[key] = clearNull(current); } return result; } if (isArray(obj)) return obj.map((item) => clearNull(item)); return obj; } const hasOwnProperty = Object.prototype.hasOwnProperty; const hasOwn = (val, key) => hasOwnProperty.call(val, key); const objectToString = Object.prototype.toString; const toTypeString = (value) => objectToString.call(value); const hasChanged = (value, oldValue) => !Object.is(value, oldValue); function sleep(ms, callback) { return new Promise( (resolve) => setTimeout(async () => { callback && await callback(); resolve(); }, ms) ); } const camelizeRE = /-(\w)/g; const camelize = (str) => { return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); }; const toPascalCase = (str) => { return str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((x) => x.charAt(0).toUpperCase() + x.slice(1).toLowerCase()).join(""); }; const toCamelCase = (str) => { const s = str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((x) => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()).join(""); return s.slice(0, 1).toLowerCase() + s.slice(1); }; const toKebabCase = (str) => str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((x) => x.toLowerCase()).join("-"); const toSnakeCase = (str) => str && str.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g).map((x) => x.toLowerCase()).join("_"); const toCharArray = (s) => [...s]; const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1); const hyphenateRE = /\B([A-Z])/g; const hyphenate = (str) => str.replace(hyphenateRE, "-$1").toLowerCase(); function replaceAll(text, repstr, newstr) { return text.replace(new RegExp(repstr, "gm"), newstr); } function trim(value) { return value.replace(/(^\s*)|(\s*$)/g, ""); } function trimAll(value) { return value.replace(/\s+/g, ""); } function getHanByNumber(num) { const HAN_STR = "\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341"; return HAN_STR.charAt(num); } function insertStr(str, start, insertStr2) { return str.slice(0, start) + insertStr2 + str.slice(start); } function escapeHTML(str) { return str.replace( /[&<>'"]/g, (tag) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", "'": "&#39;", '"': "&quot;" })[tag] || tag ); } const removeWhitespace = (str) => str.replace(/\s+/g, ""); function compareVersion(v1, v2) { const v1Arr = v1.split("."); const v2Arr = v2.split("."); const len = Math.max(v1Arr.length, v2Arr.length); while (v1Arr.length < len) v1Arr.push("0"); while (v2Arr.length < len) v2Arr.push("0"); for (let i = 0; i < len; i++) { const num1 = +v1Arr[i]; const num2 = +v2Arr[i]; if (num1 > num2) return 1; else if (num1 < num2) return -1; } return 0; } var FormatType = /* @__PURE__ */ ((FormatType2) => { FormatType2["toMinute"] = "YYYY-MM-DD HH:mm"; FormatType2["toHour"] = "YYYY-MM-DD HH"; FormatType2["toDay"] = "YYYY-MM-DD"; FormatType2["toMonth"] = "YYYY-MM"; FormatType2["toYear"] = "YYYY"; FormatType2["toSecond"] = "YYYY-MM-DD HH:mm:ss"; return FormatType2; })(FormatType || {}); function formatDate(date, format = "YYYY-MM-DD HH:mm:ss" /* toSecond */) { if (!date) date = /* @__PURE__ */ new Date(); return dayjs__default(date).format(format); } function getNow(format = "YYYY-MM-DD" /* toDay */) { return dayjs__default().format(format); } function getFirstDayOfMonth(date, format = "YYYY-MM-DD" /* toDay */) { if (!date) date = /* @__PURE__ */ new Date(); return dayjs__default(date).startOf("month").format(format); } function getLastDayOfMonth(date, format = "YYYY-MM-DD" /* toDay */) { if (!date) date = /* @__PURE__ */ new Date(); return dayjs__default(date).endOf("month").format(format); } function getDaysOfMonth(date, format = "YYYY-MM-DD" /* toDay */) { return [getFirstDayOfMonth(date, format), getLastDayOfMonth(date, format)]; } function getDaysOfLastMonth(format = "YYYY-MM-DD" /* toDay */) { const month = dayjs__default().subtract(1, "month").toDate(); return [getFirstDayOfMonth(month, format), getLastDayOfMonth(month, format)]; } function getDaysToNowOfMonth(date, format = "YYYY-MM-DD" /* toDay */) { return [getFirstDayOfMonth(date, format), getNow(format)]; } function getFirstDayOfYear(date, format = "YYYY-MM-DD" /* toDay */) { if (!date) date = /* @__PURE__ */ new Date(); return dayjs__default(date).startOf("year").format(format); } function getDaysOfWeek(format = "YYYY-MM-DD" /* toDay */) { return [dayjs__default().startOf("week").format(format), dayjs__default().endOf("week").format(format)]; } function isAfter(d1, d2 = /* @__PURE__ */ new Date()) { return dayjs__default(d2).isAfter(d1); } function isBefore(d1, d2 = /* @__PURE__ */ new Date()) { return dayjs__default(d2).isBefore(d1); } function isBetween(d1, d2, d3 = /* @__PURE__ */ new Date()) { return isAfter(d1, d3) && isBefore(d2, d3); } function addDays(days = 1, d = /* @__PURE__ */ new Date(), format = "YYYY-MM-DD" /* toDay */) { return dayjs__default(d).add(days, "day").format(format); } function subDays(days = 1, d = /* @__PURE__ */ new Date(), format = "YYYY-MM-DD" /* toDay */) { return dayjs__default(d).subtract(days, "day").format(format); } function toDate(date) { if (typeof date === "string") return dayjs__default(date).toDate(); return date.map((item) => dayjs__default(item).toDate()); } function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } const toNumber = (val) => { const n = Number.parseFloat(val); return Number.isNaN(n) ? val : n; }; const toFix = (value, n) => { n = n || 2; return Number.parseFloat(value).toFixed(n); }; function isArray(obj) { return Array.isArray(obj); } const isMap = (val) => toTypeString(val) === "[object Map]"; const isSet = (val) => toTypeString(val) === "[object Set]"; const isString = (val) => typeof val === "string"; const isDate = (val) => toTypeString(val) === "[object Date]"; const isFunction = (val) => typeof val === "function"; const isSymbol = (val) => typeof val === "symbol"; const isObject = (val) => val !== null && typeof val === "object"; const isPromise = (val) => { return isObject(val) && isFunction(val.then) && isFunction(val.catch); }; const isNumber = (val) => typeof val === "number"; const isNull = (val) => toTypeString(val) === "[object Null]"; const isUndefined = (val) => toTypeString(val) === "[object Undefined]"; const isRegExp = (val) => toTypeString(val) === "[object RegExp]"; const isFile = (val) => toTypeString(val) === "[object File]"; const isPlainObject = (val) => toTypeString(val) === "[object Object]"; function isUndef(v) { return isNull(v) || isUndefined(v); } function isEmptyString(v) { return isString(v) && v.trim().length === 0; } function isEmpty(val) { return val == null || !(Object.keys(val) || val).length; } const invokeArrayFns = (fns, arg) => { for (let i = 0; i < fns.length; i++) fns[i](arg); }; const stringHash = (str) => { let hash = 5381; let i = str.length; while (i--) hash = (hash << 5) - hash ^ str.charCodeAt(i); return hash >>> 0; }; const uuid = () => { return Array.from( { length: 16 }, () => Math.floor(Math.random() * 256).toString(16).padStart(2, "0") ).join(""); }; const urlAlphabet = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"; const nanoid = (defaultSize = 21, alphabet = urlAlphabet) => { let id = ""; let i = defaultSize; while (i--) { id += alphabet[Math.random() * 64 | 0]; } return id; }; function hideMobile(mobile) { return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2"); } const params2Url = (obj) => { const params = []; for (const key in obj) params.push(`${key}=${obj[key]}`); return encodeURIComponent(params.join("&")); }; const seconds2Time = (seconds) => { const hour = Math.floor(seconds / 3600); const minute = Math.floor((seconds - hour * 3600) / 60); const second = seconds - hour * 3600 - minute * 60; return `${fillZero(hour)}:${fillZero(minute)}:${fillZero(second)}`; }; const seconds2DayTime = (seconds) => { const day = Math.floor(seconds / 86400); const hour = Math.floor((seconds - day * 86400) / 3600); const minute = Math.floor((seconds - day * 86400 - hour * 3600) / 60); const second = seconds - day * 86400 - hour * 3600 - minute * 60; return `${fillZero(day)}:${fillZero(hour)}:${fillZero(minute)}:${fillZero(second)}`; }; function fillZero(num) { return num.toString().padStart(2, "0"); } function download(link, name) { if (!name) name = link.slice(link.lastIndexOf("/") + 1); const eleLink = document.createElement("a"); eleLink.download = name; eleLink.style.display = "none"; eleLink.href = link; document.body.appendChild(eleLink); eleLink.click(); document.body.removeChild(eleLink); } function downloadFile(name, content) { if (typeof name == "undefined") throw new Error("The first parameter name is a must"); if (typeof content == "undefined") throw new Error("The second parameter content is a must"); if (!(content instanceof Blob)) content = new Blob([content]); const link = URL.createObjectURL(content); download(link, name); } function drawImageVerify({ dom, width = 152, height = 40 }) { let imgCode = ""; const NUMBER_STRING = "0123456789"; const ctx = dom.getContext("2d"); if (!ctx) return imgCode; ctx.fillStyle = randomRgbColor(180, 230); ctx.fillRect(0, 0, width, height); for (let i = 0; i < 4; i += 1) { const text = NUMBER_STRING[randomIntegerInRange(0, NUMBER_STRING.length)]; imgCode += text; const fontSize = randomIntegerInRange(18, 41); const deg = randomIntegerInRange(-30, 30); ctx.font = `${fontSize}px Simhei`; ctx.textBaseline = "top"; ctx.fillStyle = randomRgbColor(80, 150); ctx.save(); ctx.translate(30 * i + 23, 15); ctx.rotate(deg * Math.PI / 180); ctx.fillText(text, -15 + 5, -15); ctx.restore(); } for (let i = 0; i < 5; i += 1) { ctx.beginPath(); ctx.moveTo(randomIntegerInRange(0, width), randomIntegerInRange(0, height)); ctx.lineTo(randomIntegerInRange(0, width), randomIntegerInRange(0, height)); ctx.strokeStyle = randomRgbColor(180, 230); ctx.closePath(); ctx.stroke(); } for (let i = 0; i < 41; i += 1) { ctx.beginPath(); ctx.arc(randomIntegerInRange(0, width), randomIntegerInRange(0, height), 1, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = randomRgbColor(150, 200); ctx.fill(); } return imgCode; } function rgbToHex(r, g, b) { return `#${toHex(r)}${toHex(g)}${toHex(b)}`; } function toHex(n) { if (isString(n)) n = Number.parseInt(n, 10); if (Number.isNaN(n)) return "00"; n = Math.max(0, Math.min(n, 255)); return "0123456789ABCDEF".charAt((n - n % 16) / 16) + "0123456789ABCDEF".charAt(n % 16); } function hexToRGB(hex) { if (hex.length === 4) { const text = hex.substring(1, 4); hex = `#${text}${text}`; } const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: Number.parseInt(result[1], 16), g: Number.parseInt(result[2], 16), b: Number.parseInt(result[3], 16) } : null; } function randomHexColorCode() { const n = (Math.random() * 1048575 * 1e6).toString(16); return `#${n.slice(0, 6)}`; } function randomRgbColor(min = 0, max = 255) { const r = randomIntegerInRange(min, max); const g = randomIntegerInRange(min, max); const b = randomIntegerInRange(min, max); return `rgb(${r},${g},${b})`; } function randomBoolean() { return Math.random() >= 0.5; } function randomIntegerInRange(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function randomNumberInRange(min, max) { return Math.random() * (max - min) + min; } function to(promise, errorExt) { return promise.then((data) => [null, data]).catch((err) => { if (errorExt) { const parsedError = Object.assign({}, err, errorExt); return [parsedError, void 0]; } return [err, void 0]; }); } exports.debounce = throttleDebounce.debounce; exports.throttle = throttleDebounce.throttle; exports.FormatType = FormatType; exports.addDays = addDays; exports.all = all; exports.allEqual = allEqual; exports.camelize = camelize; exports.capitalize = capitalize; exports.clearNull = clearNull; exports.clone = clone; exports.compareVersion = compareVersion; exports.download = download; exports.downloadFile = downloadFile; exports.drawImageVerify = drawImageVerify; exports.escapeHTML = escapeHTML; exports.escapeRegExp = escapeRegExp; exports.formatDate = formatDate; exports.getDaysOfLastMonth = getDaysOfLastMonth; exports.getDaysOfMonth = getDaysOfMonth; exports.getDaysOfWeek = getDaysOfWeek; exports.getDaysToNowOfMonth = getDaysToNowOfMonth; exports.getFirstDayOfMonth = getFirstDayOfMonth; exports.getFirstDayOfYear = getFirstDayOfYear; exports.getHanByNumber = getHanByNumber; exports.getLastDayOfMonth = getLastDayOfMonth; exports.getNow = getNow; exports.hasChanged = hasChanged; exports.hasOwn = hasOwn; exports.hexToRGB = hexToRGB; exports.hideMobile = hideMobile; exports.hyphenate = hyphenate; exports.insertAt = insertAt; exports.insertStr = insertStr; exports.invokeArrayFns = invokeArrayFns; exports.isAfter = isAfter; exports.isArray = isArray; exports.isBefore = isBefore; exports.isBetween = isBetween; exports.isDate = isDate; exports.isEmpty = isEmpty; exports.isEmptyString = isEmptyString; exports.isFile = isFile; exports.isFunction = isFunction; exports.isMap = isMap; exports.isNull = isNull; exports.isNumber = isNumber; exports.isObject = isObject; exports.isPlainObject = isPlainObject; exports.isPromise = isPromise; exports.isRegExp = isRegExp; exports.isSet = isSet; exports.isString = isString; exports.isSymbol = isSymbol; exports.isUndef = isUndef; exports.isUndefined = isUndefined; exports.last = last; exports.lastN = lastN; exports.nanoid = nanoid; exports.objectToString = objectToString; exports.params2Url = params2Url; exports.randomBoolean = randomBoolean; exports.randomHexColorCode = randomHexColorCode; exports.randomIntegerInRange = randomIntegerInRange; exports.randomNumberInRange = randomNumberInRange; exports.randomRgbColor = randomRgbColor; exports.removeAt = removeAt; exports.removeWhitespace = removeWhitespace; exports.replaceAll = replaceAll; exports.rgbToHex = rgbToHex; exports.seconds2DayTime = seconds2DayTime; exports.seconds2Time = seconds2Time; exports.sleep = sleep; exports.stringHash = stringHash; exports.subDays = subDays; exports.to = to; exports.toCamelCase = toCamelCase; exports.toCharArray = toCharArray; exports.toDate = toDate; exports.toFix = toFix; exports.toHex = toHex; exports.toKebabCase = toKebabCase; exports.toNumber = toNumber; exports.toPascalCase = toPascalCase; exports.toSnakeCase = toSnakeCase; exports.toTypeString = toTypeString; exports.trim = trim; exports.trimAll = trimAll; exports.uuid = uuid;