UNPKG

@buession/prototype

Version:

A native object extension framework for Javascript.

1,413 lines (1,398 loc) 44.9 kB
/*! * Buession prototype v2.2.2 * * @link https://prototype.buession.com/ * @source https://github.com/buession/buession-prototype * @copyright @ 2020-2023 Buession.com Inc. * @license MIT * @Build Time Thu, 24 Aug 2023 05:04:28 GMT */ define((function () { 'use strict'; /** * Prototype 对象 */ var Prototype = { /** * 版本 */ version: "v2.2.2", /** * 空方法 * * @return void */ emptyFunction: function () { }, /** * * @param x 任意参数 * @return 任意值 */ K: function (x) { return x; } }; window.Prototype = Prototype; /** * Try 对象 */ var Try = { /** * 接收任意数目的函数作为参数,返回第一个执行成功的函数(未抛出异常的函数)的结果 * * @return 任意函数参数执行结果 */ these: function () { var result; for (var i = 0; i < arguments.length; i++) { var lambda = arguments[i]; if (Object.isFunction(lambda)) { try { result = lambda(); break; } catch (e) { console.error(e); } } } return result; } }; window.Try = Try; /** * Optional 对象 */ var Optional = /** @class */ (function () { /** * 构造函数 * * @param value T 类型的值 */ function Optional(value) { this.value = value; } /** * 返回一个指定 T 类型的值的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例 */ Optional.of = function (value) { return new Optional(value); }; /** * 如果为非 null 或 undefined,返回 Optional 描述的指定值的实例,否则返回空的 Optional 实例 * * @param value T 类型的值 * @return T 类型的值的 Optional 实例,或空的 Optional 实例 */ Optional.ofNullable = function (value) { return Object.isUndefinedOrNull(value) ? Optional.empty() : new Optional(value); }; /** * 返回空的 Optional 实例 * * @return 空的 Optional 实例 */ Optional.empty = function () { return new Optional(null); }; /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则抛出异常 * * @return Optional 中包含这个值 */ Optional.prototype.get = function () { if (this.value === null || typeof this.value === 'undefined') { throw "No value present"; } return this.value; }; /** * 如果 value 不为 null 或 undefined,则返回 value 的值;否则返回 other * * @param other 其它值 * @return value 不为 null 或 undefined,则返回 value 的值;否则返回 other */ Optional.prototype.orElse = function (other) { return Object.isUndefinedOrNull(this.value) ? other : this.value; }; /** * 如果 value 不为 null 或 undefined,则返回 true;否则返回 false * * @return value 不为 null 或 undefined,则返回 true;否则返回 false */ Optional.prototype.isPresent = function () { return Object.isUndefinedOrNull(this.value) === false; }; return Optional; }()); window.Optional = Optional; /** * Object 对象扩展 */ /** * 获取对象数据类型 * * @param obj 对象变量 * @return 对象数据类型 */ Object.type = function (obj) { return typeof obj; }; /** * 获取对象数据类型 * * @param obj 对象变量 * @return 对象数据类型 */ Object.rawType = function (obj) { return Object.prototype.toString.call(obj).slice(8, -1); }; /** * 判断对象是否为 object 类型 * * @param obj 任意对象 * @return boolean */ Object.isObject = function (obj) { return obj !== null && typeof obj === "object"; }; /** * 判断对象是否为 object 类型 * * @param obj 任意对象 * @return boolean */ Object.isPlainObject = function (obj) { return Object.prototype.toString.call(obj) === "[object Object]"; }; /** * 判断对象是否为 Map 类型 * * @param obj 任意对象 * @return boolean */ Object.isMap = function (obj) { return Object.prototype.toString.call(obj) === "[object Map]"; }; /** * 判断对象是否为 Set 类型 * * @param obj 任意对象 * @return boolean */ Object.isSet = function (obj) { return Object.prototype.toString.call(obj) === "[object Set]"; }; /** * 判断对象是否为函数 * * @param obj 任意对象 * @return boolean */ Object.isFunction = function (obj) { return Object.type(obj) === "function"; }; /** * 判断对象是否为 Symbol * * @param obj 任意对象 * @return boolean */ Object.isSymbol = function (obj) { if (typeof obj === "symbol") { return true; } try { var toString_1 = Symbol.prototype.toString; if (typeof obj.valueOf() !== "symbol") { return false; } return /^Symbol\(.*\)$/.test(toString_1.call(obj)); } catch (e) { return false; } }; /** * 判断对象是否为 Promise * * @param obj 任意对象 * @return boolean */ Object.isPromise = function (obj) { return Object.isUndefinedOrNull(obj) === false && Object.isFunction(obj.then) && Object.isFunction(obj.catch); }; /** * 判断对象是否为原始类型 * * @param obj 任意对象 * @return boolean */ Object.isPrimitive = function (obj) { return Object.isBoolean(obj) || Object.isString(obj) || Object.isNumber(obj); }; /** * 判断对象是否为数组 * * @param obj 任意对象 * @return boolean */ Object.isArray = function (obj) { return Array.isArray(obj); }; /** * 判断对象是否为字符串对象 * * @param obj 任意对象 * @return boolean */ Object.isString = function (obj) { return Object.type(obj) === "string"; }; /** * 判断对象是否为数字对象 * * @param obj 任意对象 * @return boolean */ Object.isNumber = function (obj) { return Object.type(obj) === "number"; }; /** * 判断对象是否为布尔对象 * * @param obj 任意对象 * @return boolean */ Object.isBoolean = function (obj) { return Object.type(obj) === "boolean"; }; /** * 判断对象是否为正则对象 * * @param obj 任意对象 * @return boolean */ Object.isRegExp = function (obj) { return Object.rawType(obj) === 'RegExp'; }; /** * 判断对象是否为文件对象 * * @param obj 任意对象 * @return boolean */ Object.isFile = function (obj) { return obj instanceof File; }; /** * 判断对象是否为 windows 对象 * * @param obj 任意对象 * @return boolean */ Object.isWindow = function (obj) { return Object.isUndefinedOrNull(obj) && obj == obj.window; }; /** * 判断对象是否为 Element * * @param obj 任意对象 * @return boolean */ Object.isElement = function (obj) { if (Object.isUndefinedOrNull(obj)) { return false; } return !!(obj.nodeType == 1); }; /** * 判断对象是否为事件对象 * * @param obj 任意对象 * @return boolean */ Object.isEvent = function (obj) { return obj instanceof Event; }; /** * 判断对象是否为 null 对象 * * @param obj 任意对象 * @return boolean */ Object.isNull = function (obj) { return obj === null; }; /** * 判断对象是否为未定义 * * @param obj 任意对象 * @return boolean */ Object.isUndefined = function (obj) { return obj === undefined; }; /** * 判断对象是否为未定义或 null * * @param obj 任意对象 * @return boolean */ Object.isUndefinedOrNull = function (obj) { return Object.isUndefined(obj) || Object.isNull(obj); }; /** * 判断两个对象是否相等 * * @param obj1 一个对象 * @param obj2 用于和 obj1 比较的对象 * @return 当两个对象相等时,返回 true;否则,返回 false */ Object.equals = function (obj1, obj2) { if (obj1 === obj2) { return true; } else if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) { return false; } else if (obj1.constructor !== obj2.constructor) { return false; } else if (Object.isArray(obj1) && Object.isArray(obj2) && obj1.length === obj2.length) { for (var i = 0; i < obj1.length; i++) { if (Object.equals(obj1[i], obj2[i]) === false) { return false; } } } else if (Object.isObject(obj1) && Object.isObject(obj2) && Object.keys(obj1).length === Object.keys(obj2).length) { for (var key in obj1) { if (obj1.hasOwnProperty.call(key)) { if (Object.equals(obj1[key], obj2[key]) === false) { return false; } } } } else { return false; } return true; }; /** * 克隆对象 * * @param obj 任意对象 * @return 新对象实例 */ Object.clone = function (obj) { if (Object.isString(obj)) { return String(obj); } else if (Object.isArray(obj)) { return Array.prototype.slice.apply(obj); } else if (Object.isPlainObject(obj)) { var result_1 = Object.create(null); Object.keys(obj).forEach(function (key) { result_1[key] = Object.clone(obj[key]); }); return result_1; } return obj; }; /** * 克隆对象,但需要删除指定属性 * * @param obj 任意对象 * @param fields 需要删除的属性 * @return 新对象实例 */ Object.omit = function (obj) { var fields = []; for (var _i = 1; _i < arguments.length; _i++) { fields[_i - 1] = arguments[_i]; } var result = Object.clone(obj); for (var i = 0; i < fields.length; i++) { var key = fields[i]; delete result[key]; } return result; }; /** * Array 对象扩展 */ /** * 判断数组是否为空数组 * * @return boolean */ Array.prototype.isEmpty = function () { return this.length === 0; }; /** * 判断元素是否在数组中 * * @param item 查找对象 * @return boolean */ Array.prototype.exists = function (item) { return this.indexOf(item) !== -1; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.first = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[0]; }; /** * 获取一个元素 * * @return 第一个元素 */ Array.prototype.last = function () { if (this.length === 0) { throw "Array index out of range: 0"; } return this[this.length - 1]; }; /** * 数组迭代 * * @param callback 回调函数 * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ Array.prototype.each = Array.prototype.forEach; /** * 获取数组大小 * * @return 数组大小 */ Array.prototype.size = function () { return this.length; }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.merge = Array.prototype.concat; /** * 返回一个不包含 null/undefined 值元素的数组的新版本 * * @return 不包含 null/undefined 值元素的数组的新版本 */ Array.prototype.compact = function () { return this.filter(function (value) { return Object.isUndefinedOrNull(value); }); }; /** * 对数组的元素进行去重 * * @return 数组元素进行去重后的新版本 */ Array.prototype.unique = function () { var temp = new Array(); return this.filter(function (v) { var ret = temp.includes(v) === false; temp.push(v); return ret; }); }; /** * 返回不包括参数中任意一个指定值的数组 * * @param values 排除值数组 * @return 不包括参数中任意一个指定值的数组 */ Array.prototype.without = function () { var values = []; for (var _i = 0; _i < arguments.length; _i++) { values[_i] = arguments[_i]; } return this.filter(function (v) { return values.includes(v) === false; }); }; /** * 克隆数组 * * @return 克隆结果 */ Array.prototype.clone = function () { return this.slice(0); }; /** * 清空数组 * * @return 空数组 */ Array.prototype.clear = function () { this.length = 0; return this; }; /** * Date 对象扩展 */ /** * 判断是否为闰年 * * @return boolean */ Date.prototype.isLeapYear = function () { var year = this.getFullYear(); return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); }; /** * 获取季节 * * @return 季节 */ Date.prototype.getSeason = function () { var month = this.getMonth(); if (month >= 3 && month <= 5) { return 0; } else if (month >= 6 && month <= 8) { return 1; } else if (month >= 9 && month <= 11) { return 2; } else if (month >= 12 || month <= 2) { return 3; } else { return 0; } }; /** * 获取年份中的第几天 * * @return 年份中的第几天 */ Date.prototype.getDayOfYear = function () { var month_days = this.isLeapYear() == true ? [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var days = this.getDate(); for (var m = 0, month = this.getMonth(); m < month; m++) { days += month_days[m]; } return days; }; /** * 获取年份总天数 * * @return 年份总天数 */ Date.prototype.getDaysOfYear = function () { return this.isLeapYear() ? 366 : 365; }; /** * Format a date object into a string value. * @param format string - the desired format of the date * * The format can be combinations of the following: * * y - 年 * n - 季度(1 到 4) * N - 季度名称 * A - 季度中文名称 * M - 月 * f - 月(Jan 到 Dec) * F - 月(January 到 December) * C - 月,中文名称 * d - 日 * Y - 年份中的第几天(0 到 365) * T - 月份有几天(28 到 30) * j - 每月天数后面的英文后缀(st,nd,rd 或者 th) * e - 星期几,数字表示,0(表示星期天)到 6(表示星期六) * E - 星期几,数字表示,1(表示星期一)到 7(表示星期天) * l - 星期几,文本表示,3 个字母(Mon 到 Sun) * L - 星期几,完整的文本格式(Sunday 到 Saturday) * w - 星期几,中文名称 * W - 一月中第几个星期几 * i - 月份中的第几周 * o - 年份中的第几周 * h - 小时(1~12) * H - 小时(0~23) * m - 分 * s - 秒 * S - 毫秒 * a - 上午/下午标记 * O - 与格林威治时间相差的小时数 * P - 与格林威治时间相差的小时数,小时和分钟之间有冒号分隔 * Z - 时区 * * @return 格式化后的日期时间 */ Date.prototype.format = function (format) { if (Object.isString(format) === false) { throw "Invalid argument format"; } var $this = this; var _season_map = { "N": ["Spring", "Summer", "Autumn", "Winter"], "A": ["\u6625", "\u590f", "\u79cb", "\u51ac"] }; var _month_map = { "f": ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], "F": ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], "C": ["\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D", "\u5341", "\u5341\u4E00", "\u5341\u4E8C"] }; var _weekday_map = { "W": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], "WW": ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"], "WC": ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"] }; var season = -1; var seasonFn = function () { return Math.floor(($this.getMonth() + 3) / 3); }; var $funcs = { // 年 "y": function (pattern) { return ($this.getFullYear() + "").substring(4 - pattern.length); }, // 季度(1 到 4) "n": function () { if (season === -1) { season = seasonFn(); } return season; }, // 季度名称 "N": function () { if (season === -1) { season = seasonFn(); } return _season_map["N"][season - 1]; }, // 季度中文名称 "A": function () { if (season === -1) { season = seasonFn(); } return _season_map["A"][season - 1]; }, // 月 "M": function (pattern) { var $month = $this.getMonth() + 1; var result = $month < 10 ? "0" + $month : "" + $month; return result.substring(2 - pattern.length); }, // 月(Jan 到 Dec) "f": function () { var $month = $this.getMonth(); return _month_map["f"][$month]; }, // 月(January 到 December) "F": function () { var $month = $this.getMonth(); return _month_map["F"][$month]; }, // 月,中文名称 "C": function () { var $month = $this.getMonth(); return _month_map["C"][$month]; }, // 星期数字,0 到 6 表示 "e": function () { return $this.getDay(); }, // 星期数字,1 到 7 表示 "E": function () { return $this.getDay() + 1; }, // 星期英文缩写 "l": function () { var $weekday = $this.getDay(); return _weekday_map["W"][$weekday]; }, // 星期英文全称 "L": function () { var $weekday = $this.getDay(); return _weekday_map["WC"][$weekday]; }, // 星期中文名称 "w": function () { var $weekday = $this.getDay(); return _weekday_map["WC"][$weekday]; }, // 日 "d": function (pattern) { var $date = $this.getDate(); var result = $date < 10 ? "0" + $date : "" + $date; return result.substring(2 - pattern.length); }, // 小时 "h": function (pattern) { var $hour = $this.getHours(); var result = $hour % 12 === 0 ? "12" : $hour % 12; result = $hour < 10 ? "0" + $hour : "" + $hour; return result.substring(2 - pattern.length); }, // 小时 "H": function (pattern) { var $hour = $this.getHours(); var result = $hour < 10 ? "0" + $hour : "" + $hour; return result.substring(2 - pattern.length); }, // 分钟 "m": function (pattern) { var $minutes = $this.getMinutes(); var result = $minutes < 10 ? "0" + $minutes : "" + $minutes; return result.substring(2 - pattern.length); }, // 秒钟 "s": function (pattern) { var $seconds = $this.getSeconds(); var result = $seconds < 10 ? "0" + $seconds : "" + $seconds; return result.substring(2 - pattern.length); }, // 毫秒 "S": function (pattern) { var $mise = $this.getMilliseconds(); var result = $mise < 10 ? "0" + $mise : "" + $mise; return result.substring(2 - pattern.length); } }; return format.replace(/([ynNAMfFCdYTjeElLwWiohHmsSaOPZ])+/g, function (all, t) { var fn = $funcs[t]; return Object.isFunction(fn) === true ? fn(all) : all; }); }; /** * Document 对象扩展 */ var SameSite; (function (SameSite) { SameSite["NONE"] = "None"; SameSite["LAX"] = "Lax"; SameSite["STRICT"] = "Strict"; })(SameSite || (SameSite = {})); var CookieInstance = /** @class */ (function () { function CookieInstance() { } CookieInstance.prototype.set = function (name, value, options) { var $name = name = encodeURIComponent(name) .replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent); var $value = value ? encodeURIComponent(value) .replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent) : ''; var stringifiedAttributes = ''; if (options) { stringifiedAttributes += options.domain ? '; domain=' + options.domain : ''; stringifiedAttributes += options.path ? '; path=' + options.path : ''; if (options.expires) { var $expiresDate = options.expires instanceof Date ? options.expires : new Date(Date.now() + options.expires * 864e5); stringifiedAttributes += options.expires ? '; expires=' + $expiresDate.toUTCString() : ''; } stringifiedAttributes += options.sameSite ? '; sameSite=' + options.sameSite : ''; if (Object.isBoolean(options.secure) && options.secure) { stringifiedAttributes += options.expires ? '; secure' : ''; } if (Object.isBoolean(options.httpOnly) && options.httpOnly) { stringifiedAttributes += options.httpOnly ? '; httpOnly' : ''; } } return document.cookie = $name + '=' + $value + stringifiedAttributes; }; CookieInstance.prototype.get = function (name) { var cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0; i < cookies.length; i++) { var parts = cookies[i].split('='); var $name = decodeURIComponent(parts[0]); var $value = parts.slice(1).join('='); if ($name === name) { if ($value[0] === '"') { $value = $value.slice(1, -1); } return $value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent); } } return null; }; CookieInstance.prototype.delete = function (name, options) { var $options = options ? options : {}; $options.expires = -1; this.set(name, '', $options); }; return CookieInstance; }()); /** * 检测当前浏览器是否为全屏 * * @return 当前浏览器是否为全屏 */ Object.defineProperty(document, "fullScreen", { value: Object.isUndefined(document.fullscreen) === false ? document.fullscreen : (Object.isUndefined(document.mozFullScreen) === false ? document.mozFullScreen : (Object.isUndefined(document.webkitIsFullScreen) === false ? document.webkitIsFullScreen : (Object.isUndefined(document.msFullScreen) === false ? document.msFullScreen : (Object.isUndefined(document.fullscreenElement) === false ? document.fullscreenElement !== null : (Object.isUndefined(document.mozFullScreenElement) === false ? document.mozFullScreenElement !== null : (Object.isUndefined(document.webkitFullscreenElement) === false ? document.webkitFullscreenElement !== null : (Object.isUndefined(document.msFullscreenElement) === false ? document.msFullscreenElement !== null : false))))))), configurable: true, writable: false }); /** * 检测当前浏览器是否支持全屏模式 * * @return 当前浏览器是否支持全屏模式 */ Object.defineProperty(document, "fullScreenEnabled", { value: Object.isUndefined(document.mozFullScreenEnabled) === false ? document.mozFullScreenEnabled : (Object.isUndefined(document.webkitFullscreenEnabled) === false ? document.webkitFullscreenEnabled : (Object.isUndefined(document.msFullscreenEnabled) === false ? document.msFullscreenEnabled : (Object.isUndefined(document.fullscreenEnabled) === false ? document.fullscreenEnabled : false))), configurable: true, writable: false }); /** * 返回当前文档中正在以全屏模式显示的 Element 节点 * * @return 当前文档中正在以全屏模式显示的 Element 节点 */ Object.defineProperty(document, "fullScreenElement", { value: Object.isUndefined(document.mozFullScreenElement) === false ? document.mozFullScreenElement : (Object.isUndefined(document.webkitFullscreenElement) === false ? document.webkitFullscreenElement : (Object.isUndefined(document.msFullscreenElement) === false ? document.msFullscreenElement : (Object.isUndefined(document.fullscreenElement) === false ? document.fullscreenElement : null))), configurable: true, writable: false }); /** * 返回 Cookie 对象 * * @return Cookie 对象 */ Object.defineProperty(document, "httpCookie", { value: new CookieInstance(), configurable: true, writable: false }); /** * 请求进入全屏模式 * * @return Promise */ Document.prototype.requestFullscreen = function () { var doc = document.documentElement; if (Object.isFunction(doc.mozRequestFullScreen)) { return doc.mozRequestFullScreen(); } else if (Object.isFunction(doc.webkitRequestFullscreen)) { return doc.webkitRequestFullscreen(); } else if (Object.isFunction(doc.msRequestFullscreen)) { return doc.msRequestFullscreen(); } else { return doc.requestFullscreen(); } }; /** * 退出全屏模式 * * @return Promise */ Document.prototype.exitFullscreen = function () { if (Object.isFunction(document.mozCancelFullScreen)) { return document.mozCancelFullScreen(); } else if (Object.isFunction(document.mozExitFullScreen)) { return document.mozExitFullScreen(); } else if (Object.isFunction(document.webkitCancelFullScreen)) { return document.webkitCancelFullScreen(); } else if (Object.isFunction(document.webkitExitFullscreen)) { return document.webkitExitFullscreen(); } else if (Object.isFunction(document.msExitFullscreen)) { return document.msExitFullscreen(); } else { return document.exitFullscreen(); } }; /** * Function 对象扩展 */ /** * 获取函数参数名称 * * @return 函数参数名称列表 */ Function.prototype.argumentNames = function () { var method = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/); if (method === null) { return null; } var names = method[1].replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, "").replace(/\s+/g, "").split(", "); return names.length === 1 && !names[0] ? [] : names; }; /** * 延时执行函数 * * @param timeout 延时时间(单位:秒) * @return mixed */ Function.prototype.delay = function (timeout) { var __method = this; var args = Array.prototype.slice.call(arguments, 1); return window.setTimeout(__method.apply(__method, args), timeout * 1000); }; /** * Math 对象扩展 */ /** * 产生一个指定范围内的随机数 * * @param min 返回的最低值(默认 0) * @param max 返回的最高值 * @return 随机数 */ Math.rand = function (min, max) { min = min || 0; max = max || Number.MAX_SAFE_INTEGER; var rand = Math.random() * (max - min + 1) + min; var result = Math.round(rand); if (result < min) { return min; } else if (result > max) { return max; } else { return result; } }; /** * Number 对象扩展 */ /** * 数字填充 * * @param length 长度 * @param radix 进制 * @return 填充后的字符串数字 */ Number.prototype.toPaddedString = function (length, radix) { var str = this.toString(radix || 10); return "0".repeat(length - str.length) + str; }; /** * 判断数字是否为奇数 * * @param num 需要判断的数字 * @return boolean 数字是为奇数返回 true;否则返回 false */ Number.isOdd = function (num) { return num % 2 === 1; }; /** * 判断数字是否为偶数 * * @param num 需要判断的数字 * @return boolean 数字是为偶数返回 true;否则返回 false */ Number.isEven = function (num) { return num % 2 === 0; }; /** * 判断一个数字是否在另两个数字之间 * * @param num 需要判断的数 * @param min 最小值 * @param max 最大值 * @param match 是否包含最小值或最大值 * @return boolean 数字是否在另两个数字之间,返回 true;否则返回 false */ Number.isBetween = function (num, min, max, match) { if (match === void 0) { match = false; } min = min || 0; max = max || 0; if (min > max) { min ^= max; max ^= min; min ^= max; } return match == true ? num >= min && num <= max : num > min && num < max; }; /** * String 对象扩展 */ /** * 判断字符串是否存在 * * @param str 子字符串 * @return boolean */ String.prototype.exists = function (str) { return this.indexOf(str) >= 0; }; /** * 判断字符串是否相等 * * @param str 与此 String 进行比较的对象 * @return boolean */ String.prototype.equals = function (str) { return Object.isUndefinedOrNull(str) == false && this === str; }; /** * 判断字符串是否相等,不考虑大小写 * * @param str 与此 String 进行比较的对象 * @return boolean */ String.prototype.equalsIgnoreCase = function (str) { return str !== undefined && str !== null && this.toLowerCase() === str.toLowerCase(); }; /** * 判断是否为空字符串 * * @return boolean */ String.prototype.isEmpty = function () { return this.length === 0; }; /** * 判断是否不为空字符串 * * @return boolean */ String.prototype.isNotEmpty = function () { return this.length > 0; }; /** * 判断是否为空白字符串 * * @return boolean */ String.prototype.isBlank = function () { return /^\s*$/.test(this.toString()); }; /** * 重复一个字符串 * * @papram count 重复次数 * @return 重复后的字符串 */ String.prototype.repeat = function (count) { if (count < 1) { return ""; } else { var s = this.toString(); var result = s; for (var i = 0; i < count; i++) { result += s; } return result; } }; /** * 截取字符串左边边指定数目的字符串 * * @param length 截取长度 * @return 子字符串 */ String.prototype.left = function (length) { return this.substring(0, length); }; /** * 截取字符串右边指定数目的字符串 * * @param length 截取长度 * @return 子字符串 */ String.prototype.right = function (length) { return this.substring(this.length - length, this.length); }; /** * 截取字符串,超出部分用 truncation 替代 * * @param length 截取长度 * @param truncation 替换字符串 * @return 截取后的字符串 * 实际截取长度:当 length 小于等于 truncation 的长度时为,length;当 length 大于 truncation 的长度时为,length - truncation.length */ String.prototype.truncation = function (length, truncation) { if (truncation === void 0) { truncation = '...'; } truncation = truncation || "..."; return this.length > length ? this.slice(0, length <= truncation.length ? length : length - truncation.length) + truncation : String(this); }; /** * 删除字符串开头的空白字符 * * @return 删除了字符串最左边的空白字符的字符串 */ String.prototype.ltrim = function () { return Object.isFunction(this.trimStart) ? this.trimStart() : this.replace(/^\s*/g, ""); }; /** * 删除字符串结尾的空白字符 * * @return 删除了字符串最右边的空白字符的字符串 */ String.prototype.rtrim = function () { return Object.isFunction(this.trimEnd) ? this.trimEnd() : this.replace(/\s*$/g, ""); }; /** * 判断字符串是否以给定的字符串开头 * * @param str 搜索的字符串 * @return boolean */ String.prototype.startsWith = function (str) { return this.indexOf(str) === 0; }; /** * 判断字符串是否以给定的字符串结尾 * * @param str 搜索的字符串 * @return boolean */ String.prototype.endsWith = function (str) { var d = this.length - str.length; return d >= 0 && this.lastIndexOf(str) === d; }; /** * 首字母小写 * * @return 结果字符串 */ String.prototype.lcfirst = function () { return this.charAt(0).toLowerCase() + this.substring(1); }; /** * 首字母大写 * * @return 结果字符串 */ String.prototype.ucfirst = function () { return this.charAt(0).toUpperCase() + this.substring(1); }; /** * 将 HTML 编码 * * @return 编码后的字符串 */ String.prototype.escapeHTML = function () { return this.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;"); }; /** * 将 HTML 实体字符解码 * * @return 解码后的字符串 */ String.prototype.unescapeHTML = function () { return this.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&"); }; /** * 删除 HTML 标签 * * @param tag HTML 标签 * @returns 删除标签后的字符串 */ String.prototype.stripTag = function (tag) { return this.replace(new RegExp("<" + tag + "(\\s+(\"[^\"]*\"|'[^']*'|[^>])+)?(\/)?>|<\/" + tag + ">", "gi"), ""); }; /** * 批量删除 HTML 标签 * * @param tags 删除指定的标签 * @return 删除标签后的字符串 */ String.prototype.stripTags = function (tags) { if (typeof tags === "string") { return this.stripTag(tags); } else if (Array.isArray(tags)) { var result = this.toString(); for (var i = 0; i < tags.length; i++) { result = result.stripTag(tags[i]); } return result; } else { return this.toString(); } }; /** * 删除 script 标签 * * @return 删除 script 标签后的字符串 */ String.prototype.stripScripts = function () { return this.replace(/<script[^>]*>([\S\s]*?)<\/script>/img, ""); }; /** * 将字符串转换为数组 * * @param delimiter 分隔字符 * @return 数组 */ String.prototype.toArray = function (delimiter) { return this.split(delimiter || ""); }; /** * 返回一个数组的字符串表示形式 * * @param useDoubleQuotes 是否使用双引号引住 * @return 后的字符串 */ String.prototype.inspect = function (useDoubleQuotes) { var specialChar = { '\b': '\\b', '\t': '\\t', '\r': '\\r', '\n': '\\n', '\f': '\\f', '\\': '\\\\' }; var escapedString = this.replace(/[\x00-\x1f\\]/g, function (character) { if (character in specialChar) { return specialChar[character]; } return '\\u00' + character.charCodeAt(0).toPaddedString(2, 16); }); if (useDoubleQuotes) { return '"' + escapedString.replace(/"/g, '\\"') + '"'; } else { return "'" + escapedString.replace(/'/g, '\\\'') + "'"; } }; /** * 获取字符串 hash code * * @return 字符串 hash code */ String.prototype.hashCode = function () { var result = 0; if (result === 0 && this.length > 0) { for (var i = 0; i < this.length; i++) { result = 31 * result + this.charCodeAt(i); } } return result; }; /** * 生成随机字符串 * * @param length 生成字符串的长度 * @param type 生成类型 * NUMERIC - 数字随机字符串 * LETTER - 英文随机字符串 * LETTER_NUMERIC - 英文数字混合随机字符串 * CHINESE - 中文随机字符串 * * @return 生成结果 */ String.random = function (length, type) { if (type === void 0) { type = "LETTER_NUMERIC"; } var result = ""; if (type === "CHINESE") { for (var i = 0; i < length; i++) { result += String.fromCharCode(Math.rand(19968, 40891)); } return result; } var numeric = "0123456789"; var letter = "abcdefghijklmnopqrstuvwxyz"; var map = { "NUMERIC": numeric, "LETTER": letter + letter.toUpperCase(), "LETTER_NUMERIC": numeric + letter + letter.toUpperCase() }; if (!map[type]) { throw "Invalid argument type value, must be: NUMERIC, LETTER, LETTER_NUMERIC or CHINESE"; } for (var j = 0; j < length; j++) { result += map[type].charAt(Math.rand(0, map[type].length - 1)); } return result; }; /** * Window 对象扩展 */ Object.defineProperty(window, "browser", { value: { userAgent: navigator.userAgent, name: navigator.appName, version: navigator.appVersion, isMobile: ["Android", "iPhone", "iPod", "Windows Phone", "Mobile", "Coolpad", "mmp", "SmartPhone", "midp", "wap", "xoom", "Symbian", "J2ME", "Blackberry", "Wince"].some(function (value) { return navigator.userAgent.exists(value); }), isChrome: /\(KHTML, like Gecko\) Chrome\//.test(navigator.userAgent), isFirefox: navigator.userAgent.exists("Firefox"), isMozilla: navigator.userAgent.exists("Mozilla"), isEdge: navigator.userAgent.exists("Edge"), isMSIE: navigator.userAgent.exists("MSIE") && navigator.userAgent.exists("compatible"), isOpera: navigator.userAgent.exists("Opera"), isSafari: navigator.userAgent.exists("Safari"), isNetscape: /Netscape([\d]*)\/([^\s]+)/i.test(navigator.userAgent) }, configurable: true, writable: false }); /** * 将字符串复制到剪贴板 * * @param str 字符串 */ Window.prototype.copy = function (str) { try { if (Object.isObject(this.clipboardData)) { this.clipboardData.setData("text", str); } else { var fakeElement = document.createElement("textarea"); fakeElement.style.border = "none"; fakeElement.style.margin = "0"; fakeElement.style.padding = "0"; fakeElement.style.position = "absolute"; fakeElement.style.top = "-9999px"; fakeElement.style.left = "-9999px"; fakeElement.value = str; fakeElement.setAttribute("readonly", ""); document.body.appendChild(fakeElement); fakeElement.setSelectionRange(0, str.length); fakeElement.select(); document.execCommand("copy"); fakeElement.remove(); } } catch (e) { console.error(e); } }; /** * 获取所有的请求参数及值 * * @return 所有的请求参数及值 */ Location.prototype.getParameters = function () { var queryString = this.search; var parameters = {}; if (queryString.indexOf("?") != -1) { queryString = queryString.substring(1); var parts = queryString.split("&"); for (var i = 0; i < parts.length; i++) { var temp = parts[i].split("="); var val = temp.length == 2 ? encodeURIComponent(temp[1]) : ""; if (Object.isUndefined(parameters[temp[0]])) { parameters[temp[0]] = val; } else { if (Object.isArray(parameters[temp[0]]) == false) { var oldVal = parameters[temp[0]]; delete parameters[temp[0]]; parameters[temp[0]] = [oldVal]; } parameters[temp[0]].push(val); } } } return parameters; }; /** * 获取指定请求参数的值 * * @param name 参数名 * @return 指定请求参数的值 */ Location.prototype.getParameter = function (name) { var parameters = this.getParameters(); return parameters[name]; }; })); //# sourceMappingURL=prototype.amd.js.map