UNPKG

@librecoder/tools

Version:

![build](https://img.shields.io/badge/build-passing-success.svg)

533 lines (471 loc) 12.3 kB
/*! * tools - v1.0.5 * (c) 2021 - 2022 Qt * Released under the MIT License. */ var tools = (function (exports) { 'use strict'; function is(v) { return !!v; } function not(v) { return !v; } function isDef(v) { return v !== undefined && v !== null; } function notDef(v) { return v === undefined || v === null; } function isTrue(v) { return v === true; } function isFalse(v) { return v === false; } function isPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'symbol' || typeof v === 'boolean'; } function getType(val) { return Object.prototype.toString.call(val).slice(8, -1); } function isString(val) { return getType(val) === 'String'; } function isNumber(val) { return getType(val) === 'Number'; } function isBoolean(val) { return getType(val) === 'Boolean'; } function isFunction(val) { return getType(val) === 'Function'; } function isNull(val) { return getType(val) === 'Null'; } function isUndefined(val) { return getType(val) === 'Undefined'; } function isObject(val) { return getType(val) === 'Object'; } function isArray(val) { // return getType(val) === 'Array' return Array.isArray(val); } function isRegExp(val) { return getType(val) === 'RegExp'; } function isDate$1(val) { return getType(val) === 'Date'; } function isError(val) { return getType(val) === 'Error'; } function isSymbol(val) { return getType(val) === 'Symbol'; } function isSet(val) { return getType(val) === 'Set'; } function isMap(val) { return getType(val) === 'Map'; } function isPromise(val) { return getType(val) === 'Promise'; /*return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' )*/ } var type = /*#__PURE__*/Object.freeze({ __proto__: null, is: is, not: not, isDef: isDef, notDef: notDef, isTrue: isTrue, isFalse: isFalse, isPrimitive: isPrimitive, getType: getType, isString: isString, isNumber: isNumber, isBoolean: isBoolean, isFunction: isFunction, isNull: isNull, isUndefined: isUndefined, isObject: isObject, isArray: isArray, isRegExp: isRegExp, isDate: isDate$1, isError: isError, isSymbol: isSymbol, isSet: isSet, isMap: isMap, isPromise: isPromise }); function clone(target) { let rs; const targetType = getType(target); if (targetType === 'Object') { rs = {}; } else if (targetType === 'Array') { rs = []; } else { return target; } for (const i in target) { rs[i] = clone(target[i]); } return rs; } function hasProperty(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } // 删除数组中的某一项 function arrayRemove(arr, val) { if (arr.length) { const index = arr.indexOf(val); if (index > -1) { return arr.splice(index, 1); } } } // 删除对象中的某一项 function objectRemove(obj, key) { if (hasProperty(obj, key)) { delete obj[key]; } } function uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { return (c === 'x' ? Math.random() * 16 | 0 : 'r&0x3' | '0x8').toString(16); }); } var utils = /*#__PURE__*/Object.freeze({ __proto__: null, clone: clone, hasProperty: hasProperty, arrayRemove: arrayRemove, objectRemove: objectRemove, uuid: uuid }); function trim(s) { return s.replace(/^\s+|\s+$/gm, ''); } var string = /*#__PURE__*/Object.freeze({ __proto__: null, trim: trim }); /** * 格式化日期为指定格式的字符串 * @param d 日期对象 * @param fmt 格式化模式 * @returns {*} 日期字格式化符串 */ function formatDate(d, fmt) { var o = { "M+": d.getMonth() + 1, //月份 "d+": d.getDate(), //日 "h+": d.getHours() == 12 ? 12 : d.getHours() % 12, //小时 "H+": d.getHours(), //小时 "m+": d.getMinutes(), //分 "s+": d.getSeconds(), //秒 "q+": Math.floor((d.getMonth() + 3) / 3), //季度 "S+": d.getMilliseconds(), //毫秒 "t+": d.getHours() < 12 ? 'am' : 'pm', "T+": d.getHours() < 12 ? 'AM' : 'PM' }; if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length)); } for (var k in o) { if (new RegExp("(" + k + ")").test(fmt)) { fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(-RegExp.$1.length)); } } return fmt; } /** * 按格式解析文件为日期,由于Date.parse作为基础方法已存在,方法名使用`deformat` * @param s 日期字符串 * @param fmt 格式化模式 * @returns {Date} 日期对象 */ function parseDate(s, fmt) { if (typeof s === 'number') return new Date(s); if (!fmt) return new Date(Date.parse(s)); var d = { y: { reg: /y+/g }, M: { reg: /M+/g }, d: { reg: /d+/g }, H: { reg: /H+/g }, h: { reg: /h+/g }, m: { reg: /m+/g }, s: { reg: /s+/g }, S: { reg: /S+/g } }; for (var k in d) { var o = d[k]; var m; while ((m = o.reg.exec(fmt)) != null) { o.idx = m.index; o.len = m[0].length; o.val = parseInt(s.substr(o.idx, o.len)); } } d.y.val = d.y.val || 0; d.M.val = d.M.val || 0; d.d.val = d.d.val || 0; if (d.H.val == null || isNaN(d.H.val)) { if (!isNaN(d.h.val) && typeof d.h.val === 'number') { var am = /am/i.test(s); if (am) d.H.val = d.h.val;else d.H.val = d.h.val + 12; } else { d.H.val = 0; } } d.m.val = d.m.val || 0; d.s.val = d.s.val || 0; d.S.val = d.S.val || 0; return new Date(d.y.val, d.M.val - 1, d.d.val, d.H.val, d.m.val, d.s.val, d.S.val); } var date = /*#__PURE__*/Object.freeze({ __proto__: null, formatDate: formatDate, parseDate: parseDate }); const isEmail = s => /^([\w_\-])+@([\w_\-])+((\.[\w_\-]+){1,2})$/.test(s); const isMobile$1 = s => /^1\d{10}$/.test(s); /** * 座机 * @param s * @return {boolean} */ const isTel = s => /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(s); /** * 身份证号 * @param s * @return {boolean} */ const isIdNo = s => /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/.test(s); /** * 车牌号 * @param s * @return {boolean} */ const isCarNo = s => /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/.test(s); const isChinese = s => { return /[u4E00-u9FA5]/.test(s); }; const isUrl = s => { return /^(?:(http|https|ftp):\/\/)?((?:[\w_\-]+\.)*[\w_\-]+)(:\d+)?([^?#]*)(\?[^/?#]*)?(#.+)?$/i.test(s); }; const isDate = s => { return /^[1-2]\d{3}-(0?\d|1[0-2])-([0-2]?\d|3[0-1])$/.test(s); }; var regexp = /*#__PURE__*/Object.freeze({ __proto__: null, isEmail: isEmail, isMobile: isMobile$1, isTel: isTel, isIdNo: isIdNo, isCarNo: isCarNo, isChinese: isChinese, isUrl: isUrl, isDate: isDate }); function parseQuery(href = window.location.search) { const args = href.split('?'); if (args[0] === href) { return {}; } const obj = {}; const rs = args[1].split('#')[0].split('&'); for (let i = 0; i < rs.length; i++) { let kv = rs[i].split('='); obj[kv[0]] = kv[1]; } return obj; } function getQuery(name, href = window.location.search) { return parseQuery(href)[name]; } function asQuery(obj) { const rs = []; for (const key in obj) { const value = obj[key]; if (value.constructor === Array) { value.forEach(function (_value) { rs.push(key + '=' + _value); }); } else { rs.push(key + '=' + value); } } return rs.join('&'); } var url = /*#__PURE__*/Object.freeze({ __proto__: null, parseQuery: parseQuery, getQuery: getQuery, asQuery: asQuery }); // 是否移动端 const isMobile = () => /(nokia|iphone|android|ipad|motorola|^mot\-|softbank|foma|docomo|kddi|up\.browser|up\.link|htc|dopod|blazer|netfront|helio|hosin|huawei|novarra|CoolPad|webos|techfaith|palmsource|blackberry|alcatel|amoi|ktouch|nexian|samsung|^sam\-|s[cg]h|^lge|ericsson|philips|sagem|wellcom|bunjalloo|maui|symbian|smartphone|midp|wap|phone|windows ce|iemobile|^spice|^bird|^zte\-|longcos|pantech|gionee|^sie\-|portalmmm|jig\s browser|hiptop|^ucweb|^benq|haier|^lct|opera\s*mobi|opera\*mini|320x320|240x320|176x220)/i.test(navigator.userAgent); // 是否微信浏览器 const isWechat = () => /microMessenger/i.test(navigator.userAgent); const isAndroid = () => /android/i.test(navigator.userAgent); const isIpad = () => /ipad/i.test(navigator.userAgent); const isIphone = () => /iphone/i.test(navigator.userAgent); const isWindowsPhone = () => /Windows Phone/i.test(navigator.userAgent); const isMac = () => /macintosh/i.test(navigator.userAgent); const isWindows = () => /windows/i.test(navigator.userAgent); const isLinux = () => /linux/i.test(navigator.userAgent); const isPC = () => !isMobile(); const getAgentType = () => { let arr = []; if (isMobile()) { arr.push('mobile'); if (isWechat()) { arr.push('wechat'); } else if (isAndroid()) { arr.push('android'); } else if (isIpad()) { arr.push('iPad'); } else if (isIphone()) { arr.push('iPhone'); } else if (isWindowsPhone()) { arr.push('windowsPhone'); } } else { arr.push('pc'); if (isWechat()) { arr.push('wechat'); } else if (isMac()) { arr.push('mac'); } else if (isLinux()) { arr.push('linux'); } else if (isWindows()) { arr.push('windows'); } } return arr.join(':'); }; var device = /*#__PURE__*/Object.freeze({ __proto__: null, isMobile: isMobile, isWechat: isWechat, isAndroid: isAndroid, isIpad: isIpad, isIphone: isIphone, isWindowsPhone: isWindowsPhone, isMac: isMac, isWindows: isWindows, isLinux: isLinux, isPC: isPC, getAgentType: getAgentType }); function setCookie(key, value, options = {}) { let str = key + '=' + encodeURIComponent(value); if (options.expires) { const curr = new Date(); curr.setTime(curr.getTime() + options.expires * 3600 * 1000); options.expires = curr.toUTCString(); } for (const k in options) { str += ';' + k + '=' + options[k]; } document.cookie = str; } function getCookie(key) { let cookies = document.cookie + ';'; const start = cookies.indexOf(key); if (start <= -1) { return null; } const end = cookies.indexOf(';', start); const value = cookies.slice(start + key.length + 1, end); return decodeURIComponent(value); } function delCookie(key) { const value = getCookie(key); if (value === null) { return false; } setCookie(key, value, { expires: 0 }); } var cookie = /*#__PURE__*/Object.freeze({ __proto__: null, setCookie: setCookie, getCookie: getCookie, delCookie: delCookie }); if (!Date.format) Date.format = formatDate; if (!Date.deformat) Date.deformat = parseDate; if (!Date.prototype.clone) { Object.defineProperty(Date.prototype, 'format', { configurable: true, enumerable: false, writable: false, value: function (fmt) { return formatDate(this, fmt); } }); } /*if (!Object.prototype.clone) { Object.defineProperty(Object.prototype, 'clone', { configurable: true, enumerable: false, writable: false, value: function () { return clone(this); } }) }*/ if (String.prototype.trim) { Object.defineProperty(String.prototype, 'trim', { configurable: true, enumerable: false, writable: false, value: function () { return trim(this); } }); } exports.cookie = cookie; exports.date = date; exports.device = device; exports.regexp = regexp; exports.string = string; exports.type = type; exports.url = url; exports.utils = utils; Object.defineProperty(exports, '__esModule', { value: true }); return exports; })({});