UNPKG

@friendlyjesse/library

Version:

rollup + typescript 制作的工具函数函数库

437 lines (411 loc) 12.9 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.utils = {})); }(this, (function (exports) { 'use strict'; class EventBus { constructor() { /** * 订阅列表 */ this.event = {}; } /** * 订阅事件 * @param name - 事件名 * @param callback - 回调 */ on(name, callback) { // 一个事件可能有多个监听者 if (!this.event[name]) this.event[name] = []; this.event[name].push(callback); } /** * 触发事件 * @param {string} name - 事件名 * @param {args} args - 参数 */ emit(name, ...args) { // 遍历要触发的事件对应的数组回调函数。依次调用数组当中的函数,并把参数传入每一个cb。 this.event[name] && this.event[name].forEach(fn => { fn(...args); }); } /** * 单次触发事件 * @param {string} name - 事件名 * @param {function} callback - 回调 */ once(name, callback) { const cb = (...args) => { // eslint-disable-next-line node/no-callback-literal callback(...args); this.off(name, callback); }; this.on(name, cb); } /** * 取消事件 * @param {string=} name - 事件名 * @param {function=} callback - 事件 * @todo 如果没有传入参数,则移除所有事件监听器 * @todo 如果只提供了事件名(eventName),则移除该事件名对应的所有监听器 * @todo 如果同时提供了事件与回调,则只移除这个事件回调的监听器 */ off(name, callback) { if (name === undefined) { // 没有传入参数,移除所有监听器 this.event = {}; } else if (this.event[name]) { if (!callback) { // 只提供事件名, 移除该事件名对应的所有的监听器 delete this.event[name]; return; } const index = this.event[name].findIndex(fn => callback === fn); // 通过索引删除掉对应回调数组中的回调函数。 this.event[name].splice(index, 1); // 回调数组长度为0时,移除事件 if (!this.event[name].length) delete this.event[name]; } else { throw Error('不存在该事件!'); } } } /** * 判断`obj`是否为空 * @category Object * @param obj */ function isEmptyObject(obj) { if (!obj || typeof obj !== 'object' || Array.isArray(obj)) { return false; } return !Object.keys(obj).length; } /** * 判断是否为数组 * @category Array * @param arr * @returns 返回一个 boolean */ function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; } /** * 深拷贝 * @category Object * @param obj * @returns 拷贝后的值 */ function deepClone(obj) { // 对常见的“非”值,直接返回原来值 if ([null, undefined, NaN, false].includes(obj)) return obj; if (typeof obj !== 'object' && typeof obj !== 'function') { // 原始类型直接返回 return obj; } const o = isArray(obj) ? [] : {}; for (const i in obj) { if (i in obj) { o[i] = typeof obj[i] === 'object' ? deepClone(obj[i]) : obj[i]; } } return o; } /** * 判断是否为对象 * @category Object * @param param * @returns 返回一个 boolean */ function isObject(param) { return Object.prototype.toString.call(param) === '[object Object]'; } /** * 判断两个数组是否相等 * @category Array * @param arr1 * @param arr2 */ function arrayEqual(arr1, arr2) { if (arr1 === arr2) return true; if (arr1.length !== arr2.length) return false; for (let i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) return false; } return true; } /** * 根据`id`给数组分类 * @category Array * @param arr * @param id */ function arrayClassify(arr, id) { const mp = {}; const ret = []; arr.forEach(item => { if (typeof mp[id] === 'number') { ret[mp[id]].push(item); } else { mp[id] = ret.length; ret.push([item]); } }); return ret; } /** * 格式化时间戳 * @category Formatter * @param 时间戳 */ function formatTime(Timestamp) { const date = new Date(Timestamp); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hours = date.getHours(); const minu = date.getMinutes(); const second = date.getSeconds(); // 判断是否满10 const arr = [month, day, hours, minu, second]; return year + '-' + arr[0] + '-' + arr[1] + ' ' + arr[2] + ':' + arr[3] + ':' + arr[4]; } /** * 字符串转为ArrayBuffer对象,参数为字符串 * @category ArrayBuffer * @param u - string * @param f - callback */ function str2ab(s, f) { const b = new Blob([s], { type: 'text/plain' }); const r = new FileReader(); r.readAsArrayBuffer(b); // eslint-disable-next-line no-useless-call r.onload = function () { if (f) f.call(null, r.result); }; } /** * ArrayBuffer转为字符串,参数为ArrayBuffer对象 * @category ArrayBuffer * @param u - arraybuffer * @param f - callback */ function ab2str(u, f) { const b = new Blob([u]); const r = new FileReader(); r.readAsText(b, 'utf-8'); // eslint-disable-next-line no-useless-call r.onload = function () { if (f) f.call(null, r.result); }; } /** * 获取 json 的 keys 或 values * @category JSON * @param json - json * @param type - 'keys' / 'values' * @returns 获取的 keys 或 values */ function getDeepJSON(json, type = 'values') { let values = []; Object[type](json).forEach((item) => { if (Object.prototype.toString.call(item) === '[object Object]') { values = values.concat(getDeepJSON(item)); } else { values.push(item); } }); return values; } /** * json 转 params * @category JSON * @param json - json * @param slice - 分隔符 * @returns 转换后的 json */ function json2params(json, slice = '&') { return Object.keys(json).reduce((acc, item) => { return String(acc) + encodeURIComponent(item) + '=' + encodeURIComponent(isObject(json[item]) ? JSON.stringify(json[item]) : json[item]) + slice; }, '').slice(0, -1); } /** * 获取 url 的 path 和 params * @param url * @returns path 和 params */ function getUrlResolve(url) { let path = ''; const params = {}; if (url.indexOf('?') > -1) { const str = url.split('?'); path = str[0]; const strs = str[1].split('&'); for (let i = 0; i < strs.length; i++) { params[strs[i].split('=')[0]] = strs[i].split('=')[1]; // 如果出现乱码的话,可以用decodeURI()进行解码 } } return { path, params }; } /** * 判断是否为URL地址 * @category Validate * @param str */ function isUrl(str) { return /[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/i.test(str); } /** * 判断是否为手机号 * @category Validate * @param str */ function isPhoneNum(str) { return /^(\+?0?86-?)?1[3456789]\d{9}$/.test(str); } /** * 判断是否为邮箱地址 * @category Validate * @param str */ function isEmail(str) { return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(str); } /** * 判断是否为身份证号 * @category Validate * @param str */ function isIdCard(str) { return /^(^[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(str); } /** * 获取浏览器类型和版本 * @category OS */ function getExplore() { const sys = {}; const ua = navigator.userAgent.toLowerCase(); let s; /* eslint-disable */ (s = ua.match(/rv:([\d.]+)\) like gecko/)) ? sys.ie = s[1] : (s = ua.match(/msie ([\d\.]+)/)) ? sys.ie = s[1] : (s = ua.match(/edge\/([\d\.]+)/)) ? sys.edge = s[1] : (s = ua.match(/firefox\/([\d\.]+)/)) ? sys.firefox = s[1] : (s = ua.match(/(?:opera|opr).([\d\.]+)/)) ? sys.opera = s[1] : (s = ua.match(/chrome\/([\d\.]+)/)) ? sys.chrome = s[1] : (s = ua.match(/version\/([\d\.]+).*safari/)) ? sys.safari = s[1] : 0; /* eslint-disable */ // 根据关系进行判断 if (sys.ie) return ('IE: ' + sys.ie); if (sys.edge) return ('EDGE: ' + sys.edge); if (sys.firefox) return ('Firefox: ' + sys.firefox); if (sys.chrome) return ('Chrome: ' + sys.chrome); if (sys.opera) return ('Opera: ' + sys.opera); if (sys.safari) return ('Safari: ' + sys.safari); return 'Unkonwn'; } /** * 获取操作系统类型 * @category OS */ function getOS() { /* eslint-disable */ const userAgent = 'navigator' in window && 'userAgent' in navigator && navigator.userAgent.toLowerCase() || ''; const appVersion = 'navigator' in window && 'appVersion' in navigator && navigator.appVersion.toLowerCase() || ''; /* eslint-disable */ if (/iphone/i.test(userAgent) || /ipad/i.test(userAgent) || /ipod/i.test(userAgent)) return 'ios'; if (/android/i.test(userAgent)) return 'android'; if (/win/i.test(appVersion) && /phone/i.test(userAgent)) return 'windowsPhone'; if (/mac/i.test(appVersion)) return 'MacOSX'; if (/win/i.test(appVersion)) return 'windows'; if (/linux/i.test(appVersion)) return 'linux'; } /** * 读取cookie * @category Cookie * @param name */ function getCookie(name) { const arr = document.cookie.replace(/\s/g, '').split(';'); for (let i = 0; i < arr.length; i++) { const tempArr = arr[i].split('='); if (tempArr[0] === name) { return decodeURIComponent(tempArr[1]); } } return ''; } /** * 设置 Cookie * @category Cookie * @param name * @param value * @param days */ function setCookie(name, value, days) { const date = new Date(); date.setDate(date.getDate() + days); document.cookie = name + '=' + value + ';expires=' + date; } /** * 删除 cookie * @category Cookie * @param name */ function removeCookie(name) { // 设置已过期,系统会立刻删除cookie setCookie(name, '1', -1); } exports.EventBus = EventBus; exports.ab2str = ab2str; exports.arrayClassify = arrayClassify; exports.arrayEqual = arrayEqual; exports.deepClone = deepClone; exports.formatTime = formatTime; exports.getCookie = getCookie; exports.getDeepJSON = getDeepJSON; exports.getExplore = getExplore; exports.getOS = getOS; exports.getUrlResolve = getUrlResolve; exports.isArray = isArray; exports.isEmail = isEmail; exports.isEmptyObject = isEmptyObject; exports.isIdCard = isIdCard; exports.isObject = isObject; exports.isPhoneNum = isPhoneNum; exports.isUrl = isUrl; exports.json2params = json2params; exports.removeCookie = removeCookie; exports.setCookie = setCookie; exports.str2ab = str2ab; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=bundle.umd.js.map