@oipage/core.js 1.0.0 → 1.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG +52 -6
  2. package/LICENSE +20 -20
  3. package/README.md +170 -51
  4. package/dist/core.esm.js +2711 -0
  5. package/dist/core.js +2709 -208
  6. package/dist/core.min.js +2 -6
  7. package/package.json +63 -34
  8. package/src/Array/group.js +35 -0
  9. package/src/Array/index.js +21 -0
  10. package/src/Array/list.js +79 -0
  11. package/src/Array/sort.js +40 -0
  12. package/src/Array/tool.js +20 -0
  13. package/src/Array/unique.js +30 -0
  14. package/src/Cache/driver.js +86 -0
  15. package/src/Cache/expire.js +21 -0
  16. package/src/Cache/index.js +33 -0
  17. package/src/Cache/store.js +113 -0
  18. package/src/Color/adjust.js +67 -0
  19. package/src/Color/convert.js +100 -0
  20. package/src/Color/index.js +19 -0
  21. package/src/Color/tool.js +39 -0
  22. package/src/Digits/compare.js +33 -0
  23. package/src/Digits/format.js +55 -0
  24. package/src/Digits/index.js +32 -9
  25. package/src/Digits/math.js +75 -0
  26. package/src/Digits/precise.js +230 -0
  27. package/src/Digits/tool.js +29 -0
  28. package/src/Id/index.js +17 -0
  29. package/src/Id/nanoid.js +24 -0
  30. package/src/Id/random.js +40 -0
  31. package/src/Id/tool.js +38 -0
  32. package/src/Id/uuid.js +21 -0
  33. package/src/Object/check.js +15 -0
  34. package/src/Object/clone.js +66 -0
  35. package/src/Object/equal.js +63 -0
  36. package/src/Object/index.js +25 -0
  37. package/src/Object/merge.js +35 -0
  38. package/src/Object/path.js +58 -0
  39. package/src/Object/pick.js +34 -0
  40. package/src/Query/index.js +14 -0
  41. package/src/Query/parse.js +40 -0
  42. package/src/Query/stringify.js +45 -0
  43. package/src/Query/tool.js +58 -0
  44. package/src/Query/url.js +63 -0
  45. package/src/String/case.js +35 -0
  46. package/src/String/escape.js +40 -0
  47. package/src/String/index.js +28 -0
  48. package/src/String/mask.js +70 -0
  49. package/src/String/pad.js +23 -0
  50. package/src/String/trim.js +10 -0
  51. package/src/String/truncate.js +36 -0
  52. package/src/String/width.js +27 -0
  53. package/src/Time/arithmetic.js +61 -0
  54. package/src/Time/calendar.js +37 -0
  55. package/src/Time/compare.js +28 -0
  56. package/src/Time/field.js +37 -0
  57. package/src/Time/format.js +28 -0
  58. package/src/Time/index.js +97 -74
  59. package/src/Time/tool.js +20 -16
  60. package/src/Validate/contact.js +14 -0
  61. package/src/Validate/identity.js +57 -0
  62. package/src/Validate/index.js +24 -0
  63. package/src/Validate/network.js +59 -0
  64. package/src/Validate/type.js +28 -0
  65. package/src/index.js +10 -2
  66. package/src/shared/date.js +123 -0
  67. package/src/shared/is.js +63 -0
  68. package/src/tool.js +2 -2
  69. package/types/Array.d.ts +33 -0
  70. package/types/Cache.d.ts +51 -0
  71. package/types/Color.d.ts +43 -0
  72. package/types/Digits.d.ts +92 -0
  73. package/types/Id.d.ts +25 -0
  74. package/types/Object.d.ts +45 -0
  75. package/types/Query.d.ts +35 -0
  76. package/types/String.d.ts +62 -0
  77. package/types/Time.d.ts +136 -0
  78. package/types/Validate.d.ts +39 -0
  79. package/types/index.d.ts +30 -5
  80. package/.github/FUNDING.yml +0 -12
  81. package/.mailmap +0 -1
  82. package/AUTHORS.txt +0 -6
  83. package/types/Digits.ts +0 -13
  84. package/types/Time.ts +0 -52
package/dist/core.min.js CHANGED
@@ -1,9 +1,5 @@
1
1
  /*!
2
- * @oipage/corejs v1.0.0
2
+ * @oipage/core.js v1.1.0-alpha.0
3
3
  * git+https://github.com/oi-contrib/oipage-corejs.git
4
4
  */
5
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).corejs={})}(this,function(t){"use strict";
6
- /*!
7
- * format of OIPage v1.4.1
8
- * git+https://github.com/oi-contrib/OIPage.git
9
- */function e(t,e){var i;if(e=e||e,t){if("object"==typeof t&&t.constructor===Date)i=t;else if(!e.inputFormat&&(i=new Date(t))+""=="Invalid Date")return console.error("非法的日期格式:"+t,i),""}else i=new Date;var s={yyyy:0,MM:0,dd:0,HH:0,mm:0,ss:0};if(i)s.yyyy=i.getFullYear(),s.MM=i.getMonth()+1,s.dd=i.getDate(),s.HH=i.getHours(),s.mm=i.getMinutes(),s.ss=i.getSeconds();else for(var n=e.inputFormat+"",r=0,o=0;o<n.length;o++)if("yyyy"==n.substring(o,o+4))s.yyyy=+t.substring(r,r+4),r+=4,o+=3;else{var a=n.substring(o,o+2);if(["MM","dd","HH","mm","ss"].indexOf(a)>-1){var y=t[r];/\d/.test(t[r+1])?(y+=t[r+1],r+=2):r+=1,s[a]=+y,o+=1}else r+=1}return s.MM<10&&(s.MM="0"+s.MM),s.dd<10&&(s.dd="0"+s.dd),s.HH<10&&(s.HH="0"+s.HH),s.mm<10&&(s.mm="0"+s.mm),s.ss<10&&(s.ss="0"+s.ss),(e.format||"yyyy/MM/dd").replace("yyyy",s.yyyy).replace("MM",s.MM).replace("dd",s.dd).replace("HH",s.HH).replace("mm",s.mm).replace("ss",s.ss)}function i(t,i={}){if(this.inputFormat=i.input||"yyyy/MM/dd",this.outputFormat=i.output||"yyyy/MM/dd",t&&"string"==typeof t){let i=e(t,{inputFormat:this.inputFormat}).split("/");this.year=+i[0],this.month=+i[1],this.day=+i[2]}else s=t,n="Date",Object.prototype.toString.call(s)!=="[object "+n+"]"&&(t=new Date),this.year=t.getFullYear(),this.month=t.getMonth()+1,this.day=t.getDate();var s,n}function s(t=0){this.value=t}i.prototype.valueOf=function(){return e(`${this.year}/${this.month}/${this.day}`,{format:this.outputFormat})},i.prototype.addYear=function(t){return this.year+=t,this},i.prototype.addMonth=function(t){let e=t%12;if(this.year+=(t-e)/12,e>0){let t=12-this.month;t>=e?this.month+=e:(this.year+=1,this.month=e-t)}else e<0&&(this.month+e>0?this.month+=e:(this.year-=1,this.month+=12+e));let i=function(t,e){return 2==e?t%4!=0||t%100==0&&t%400!=0?28:29:[31,-1,31,30,31,30,31,31,30,31,30,31][e-1]}(this.year,this.month);return i<this.day&&(this.day=i),this},i.prototype.addDay=function(t){let e=new Date(+new Date(`${this.year}/${this.month}/${this.day}`)+864e5*t);return this.year=e.getFullYear(),this.month=e.getMonth()+1,this.day=e.getDate(),this},s.prototype.format=function(){return function(t){if(t||0===t){var e,i;if(-1==(t+="").indexOf("."))e=".00",i=t;else{var s=t.split(".");e="."+(s[1]+"0").substring(0,2),i=s[0]}for(var n=[],r=i.length;r>0;r-=3)n.unshift(i.substring(r>2?r-3:0,r));return n.join(",")+e}return""}(this.value)},t.Digits=s,t.Time=i});
5
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).corejs={})}(this,function(t){"use strict";const e=["yyyy","MM","dd","HH","mm","ss","yy","M","d"],r={yyyy:"(\\d{4})",yy:"(\\d{2})",MM:"(\\d{1,2})",M:"(\\d{1,2})",dd:"(\\d{1,2})",d:"(\\d{1,2})",HH:"(\\d{1,2})",mm:"(\\d{1,2})",ss:"(\\d{1,2})"};function n(t){return t<10?"0"+t:""+t}function i(t){return t%4==0&&t%100!=0||t%400==0}function o(t,e){return[31,i(t)?29:28,31,30,31,30,31,31,30,31,30,31][e-1]}function u(t,e,r){let n=new Date(2e3,0,1,0,0,0,0);return n.setFullYear(t,e-1,r),n}function s(t,e,r){return"number"==typeof t&&isFinite(t)&&t===Math.floor(t)&&"number"==typeof e&&e===Math.floor(e)&&e>=1&&e<=12&&"number"==typeof r&&r===Math.floor(r)&&r>=1&&r<=o(t,e)}const a=Object.prototype.toString;function f(t,e){return a.call(t)==="[object "+e+"]"}function l(t){return"number"==typeof t&&isFinite(t)&&Math.floor(t)===t}function c(t){return f(t,"Date")}function h(t){return f(t,"RegExp")}function p(t){return f(t,"Map")}function g(t){return f(t,"Set")}const y=Function.prototype.toString.call(Object);function d(t){if(!f(t,"Object"))return!1;let e=Object.getPrototypeOf(t);if(null===e)return!0;let r=Object.prototype.hasOwnProperty.call(e,"constructor")&&e.constructor;return"function"==typeof r&&Function.prototype.toString.call(r)===y}function m(t){return null==t}function b(t,e,r){let n=new Date(0);return n.setUTCFullYear(t,e-1,r),n.setUTCHours(0,0,0,0),n.getTime()}function w(t,n){let i,u,a;if(n=n||{},Object.defineProperty(this,"inputFormat",{value:n.input||"yyyy/MM/dd",writable:!0,enumerable:!1}),Object.defineProperty(this,"outputFormat",{value:n.output||"yyyy/MM/dd",writable:!0,enumerable:!1}),null==t||""===t){let t=new Date;i=t.getFullYear(),u=t.getMonth()+1,a=t.getDate()}else if("string"==typeof t){let n=function(t,n){let i="",u=[],s=0;for(;s<n.length;){let t=null;for(let r=0;r<e.length;r++)if(n.substring(s,s+e[r].length)===e[r]){t=e[r];break}t?(i+=r[t],u.push(t),s+=t.length):(i+="[^0-9]?",s+=1)}let a=new RegExp("^"+i).exec(String(t).trim());if(!a)throw new TypeError("无法按格式 "+n+" 解析日期:"+t);let f=null,l=null,c=null;for(let t=0;t<u.length;t++){let e=+a[t+1];switch(u[t]){case"yyyy":f=e;break;case"yy":f=e<=49?2e3+e:1900+e;break;case"MM":case"M":l=e;break;case"dd":case"d":c=e}}if(null===f||null===l||null===c)throw new TypeError("格式 "+n+" 中缺少年、月、日:"+t);if(l<1||l>12||c<1||c>o(f,l))throw new TypeError("非法的日期:"+t);return{year:f,month:l,day:c}}(t,this.inputFormat);i=n.year,u=n.month,a=n.day}else if("number"==typeof t){if(!isFinite(t))throw new TypeError("非法的日期时间戳:"+t);let e=new Date(t);i=e.getFullYear(),u=e.getMonth()+1,a=e.getDate()}else{if(!c(t))throw new TypeError("Time 只接受字符串、Date 对象或时间戳,收到:"+t);if(isNaN(t.getTime()))throw new TypeError("非法的 Date 对象");i=t.getFullYear(),u=t.getMonth()+1,a=t.getDate()}if(!s(i,u,a))throw new TypeError("非法的日期:"+t);this.year=i,this.month=u,this.day=a}!function(t){t.prototype.isValid=function(){return s(this.year,this.month,this.day)},t.prototype.clone=function(){return new t(this.getTime(),{input:this.inputFormat,output:this.outputFormat})},t.prototype.getTime=function(){return u(this.year,this.month,this.day).getTime()},t.prototype.toDate=function(){return u(this.year,this.month,this.day)}}(w),function(t){t.prototype.format=function(t){return function(t,e,r,i){return String(i).replace(/yyyy|MM|dd|HH|mm|ss|yy|M|d/g,function(i){switch(i){case"yyyy":return""+t;case"yy":return n(t%100);case"MM":return n(e);case"M":return""+e;case"dd":return n(r);case"d":return""+r;default:return"00"}})}(this.year,this.month,this.day,t||this.outputFormat)},t.prototype.valueOf=function(){return this.format()},t.prototype.toString=function(){return this.format()},t.prototype.toJSON=function(){return this.format()}}(w),function(t){t.prototype.addYear=function(t){if(!l(t))throw new TypeError("addYear 需要整数,收到:"+t);this.year+=t;let e=o(this.year,this.month);return e<this.day&&(this.day=e),this},t.prototype.addMonth=function(t){if(!l(t))throw new TypeError("addMonth 需要整数,收到:"+t);let e=12*this.year+this.month-1+t;this.year=Math.floor(e/12),this.month=e-12*this.year+1;let r=o(this.year,this.month);return r<this.day&&(this.day=r),this},t.prototype.addDay=function(t){if(!l(t))throw new TypeError("addDay 需要整数,收到:"+t);let e=this.toDate();return e.setDate(e.getDate()+t),this.year=e.getFullYear(),this.month=e.getMonth()+1,this.day=e.getDate(),this},t.prototype.addWeek=function(t){if(!l(t))throw new TypeError("addWeek 需要整数,收到:"+t);return this.addDay(7*t)}}(w),function(t){t.prototype.diffDays=function(e){let r=function(t,e,r){if(e instanceof t)return e;if(c(e)||"number"==typeof e)return new t(e);if("string"==typeof e)return new t(e,r?{input:r,output:r}:void 0);throw new TypeError("无法转换为 Time 的参数:"+e)}(t,e,this.inputFormat),n=b(this.year,this.month,this.day),i=b(r.year,r.month,r.day);return Math.round((n-i)/864e5)},t.prototype.isBefore=function(t){return this.diffDays(t)<0},t.prototype.isAfter=function(t){return this.diffDays(t)>0},t.prototype.isSame=function(t){return 0===this.diffDays(t)}}(w),function(t){t.prototype.startOfMonth=function(){return this.day=1,this},t.prototype.endOfMonth=function(){return this.day=o(this.year,this.month),this},t.prototype.getWeekDay=function(){return this.toDate().getDay()},t.prototype.isLeapYear=function(){return i(this.year)},t.prototype.daysInMonth=function(){return o(this.year,this.month)}}(w),w.today=function(t){return new w(void 0,t)},w.parse=function(t,e){return new w(t,{input:e,output:e})};const v="function"==typeof BigInt,M=v?BigInt(10):10,A=v?BigInt(0):0,S=v?BigInt(2):2,E=/^([+-]?)(\d+)?(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,j=["half-up","half-even","ceil","floor","trunc"];function O(t){let e=BigInt(1);for(let r=0;r<t;r++)e*=M;return e}function T(t){return t<A?-t:t}function F(t,e){for(;e>0&&t%M===A;)t/=M,e-=1;return{big:t,scale:e}}function I(t){if(-1===j.indexOf(t))throw new TypeError("不支持的舍入模式:"+t+",可选 "+j.join("、"));return t}function k(t){if(!v)throw new TypeError("当前运行环境不支持 BigInt,Digits 无法使用:请升级小程序基础库 / iOS 14+ / Node 10.4+");if(t&&"object"==typeof t&&"bigint"==typeof t.big)return t;if("bigint"==typeof t)return{big:t,scale:0};let e;if("number"==typeof t){if(!isFinite(t))throw new TypeError("不是合法的数字:"+t);e=String(t)}else{if("string"!=typeof t)throw new TypeError("不是合法的数字:"+t);e=t.trim().replace(/,/g,"")}let r=E.exec(e);if(!r||!r[2]&&!r[3])throw new TypeError("不是合法的数字:"+t);let n="-"===r[1],i=r[2]||"",o=r[3]||"",u=r[4]?parseInt(r[4],10):0,s=i+o,a=o.length-u;a<0&&(s+="0".repeat(-a),a=0),s=s.replace(/^0+(?=\d)/,"");let f=BigInt(s);return n&&(f=-f),F(f,a)}function _(t){let e=t.big<A,r=(e?-t.big:t.big).toString(),n=t.scale;if(0===n)return(e?"-":"")+r;r.length<=n&&(r="0".repeat(n-r.length+1)+r);let i=r.length-n;return(e?"-":"")+r.substring(0,i)+"."+r.substring(i)}function x(t,e,r,n,i){if(e===A)return t;let o=e*S;switch(i){case"half-up":o>=r&&(t+=BigInt(1));break;case"half-even":(o>r||o===r&&t%S!==A)&&(t+=BigInt(1));break;case"ceil":n||(t+=BigInt(1));break;case"floor":n&&(t+=BigInt(1))}return t}function D(t,e,r){if(t=k(t),e=void 0===e?0:e,r=I(r||"half-up"),e<0)throw new RangeError("scale 不能为负数:"+e);if(t.scale<=e)return{big:t.big*O(e-t.scale),scale:e};let n=t.big<A,i=O(t.scale-e),o=T(t.big)/i;return o=x(o,T(t.big)%i,i,n,r),F(n?-o:o,e)}function B(t,e){let r=_(t),n=r.indexOf(".");if(-1===n)return 0===e?r:r+"."+"0".repeat(e);let i=r.length-n-1;return i>=e?r:r+"0".repeat(e-i)}function $(t=0){Object.defineProperty(this,"_decimal",{value:k(t),writable:!0,enumerable:!1}),Object.defineProperty(this,"value",{enumerable:!0,get:function(){return t=this._decimal,Number(_(t));var t},set:function(t){this._decimal=k(t)}})}!function(t){t.prototype.format=function(t,e){t=void 0===t?2:t,e=e||{};let r=B(D(this._decimal,t,e.rounding||"half-up"),t);return!1===e.thousands?r:function(t){let e="-"===t.charAt(0),r=e?t.substring(1):t,n=r.indexOf("."),i=-1===n?r:r.substring(0,n),o=-1===n?"":r.substring(n);return(e?"-":"")+i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+o}(r)},t.prototype.toString=function(){return _(this._decimal)},t.prototype.valueOf=function(){return this.value},t.prototype.toJSON=function(){return this.value},t.prototype.getValue=function(){return this.value},t.prototype.toFixed=function(t,e){return t=void 0===t?2:t,B(D(this._decimal,t,e),t)}}($),function(t){t.prototype.add=function(t){return this._decimal=function(t,e){t=k(t),e=k(e);let r=Math.max(t.scale,e.scale);return F(t.big*O(r-t.scale)+e.big*O(r-e.scale),r)}(this._decimal,t),this},t.prototype.subtract=function(t){return this._decimal=function(t,e){t=k(t),e=k(e);let r=Math.max(t.scale,e.scale);return F(t.big*O(r-t.scale)-e.big*O(r-e.scale),r)}(this._decimal,t),this},t.prototype.multiply=function(t){var e,r;return this._decimal=(e=this._decimal,r=t,e=k(e),r=k(r),F(e.big*r.big,e.scale+r.scale)),this},t.prototype.divide=function(t,e){return e=e||{},this._decimal=function(t,e,r,n){if(t=k(t),(e=k(e)).big===A)throw new RangeError("除数不能为0");r=void 0===r?16:r,n=I(n||"half-up");let i=t.big<A!=e.big<A,o=T(t.big)*O(e.scale+r),u=T(e.big)*O(t.scale),s=o/u;return s=x(s,o%u,u,i,n),F(i?-s:s,r)}(this._decimal,t,void 0===e.scale?16:e.scale,e.rounding),this},t.prototype.round=function(t,e){return this._decimal=D(this._decimal,t,e),this},t.prototype.abs=function(){return this._decimal.big<BigInt(0)&&(this._decimal={big:-this._decimal.big,scale:this._decimal.scale}),this},t.prototype.negate=function(){return this._decimal={big:-this._decimal.big,scale:this._decimal.scale},this}}($),function(t){t.prototype.compare=function(t){return function(t,e){t=k(t),e=k(e);let r=Math.max(t.scale,e.scale),n=t.big*O(r-t.scale),i=e.big*O(r-e.scale);return n===i?0:n>i?1:-1}(this._decimal,t)},t.prototype.eq=function(t){return 0===this.compare(t)},t.prototype.gt=function(t){return this.compare(t)>0},t.prototype.gte=function(t){return this.compare(t)>=0},t.prototype.lt=function(t){return this.compare(t)<0},t.prototype.lte=function(t){return this.compare(t)<=0}}($);const C=/[\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/;function P(t){return Array.from(String(t))}function z(t){return C.test(t)?2:1}function R(t){let e=0;return P(t).forEach(function(t){e+=z(t)}),e}const U={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},H={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&#x27;":"'"};function L(t,e,r,n){n=void 0===n?"*":String(n);let i=P(t);return e=Math.max(0,e||0),r=Math.max(0,r||0),i.length<=e+r?n.repeat(i.length):i.slice(0,e).join("")+n.repeat(i.length-e-r)+i.slice(i.length-r).join("")}const N={trim:function(t){return String(t).replace(/^[\s\u00A0\u3000]+|[\s\u00A0\u3000]+$/g,"")},width:R,widthOf:z,truncate:function(t,e,r){r=void 0===r?"...":r;let n=P(t);return n.length<=e?String(t):n.slice(0,Math.max(0,e-Array.from(String(r)).length)).join("")+r},cutByWidth:function(t,e,r){let n=R(r=void 0===r?"...":r);if(R(t)<=e)return String(t);let i=0,o=[],u=P(t);for(let t=0;t<u.length;t++){let r=z(u[t]);if(i+r>e-n)break;i+=r,o.push(u[t])}return o.join("")+r},pad:function(t,e,r,n){t=String(t),r=void 0===r?" ":String(r);let i=R(t);if(i>=e)return t;let o="";for(;i+R(o)+R(r)<=e;)o+=r;return"start"===n?o+t:t+o},camelCase:function(t){return String(t).split(/[\s\-_./]+/).filter(Boolean).map(function(t,e){let r=t.toLowerCase();return 0===e?r:r.charAt(0).toUpperCase()+r.substring(1)}).join("")},kebabCase:function(t){return String(t).replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[\s_./]+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"").toLowerCase()},reverse:function(t){return P(t).reverse().join("")},mask:function(t,e,r){if(!(t=String(null==t?"":t)))return"";let n=(r=r||{}).char||"*";switch(e){case"mobile":return L(t,3,4,n);case"idcard":return L(t,6,4,n);case"bankcard":{let e=P(t).slice(-4).join(""),r=[];for(let t=0;t<3;t++)r.push(n.repeat(4));return r.join(" ")+" "+e}case"email":{let e=t.indexOf("@");if(e<=0)return L(t,2,2,n);let r=t.substring(0,e),i=t.substring(e);return r.length<=2?n.repeat(r.length)+i:r.substring(0,2)+n.repeat(3)+i}case"name":{let e=P(t);return 1===e.length?n:2===e.length?e[0]+n:e[0]+n.repeat(e.length-2)+e[e.length-1]}default:return L(t,r.head||0,r.tail||0,n)}},maskMiddle:L,escapeHTML:function(t){return String(t).replace(/[&<>"']/g,function(t){return U[t]})},unescapeHTML:function(t){return String(t).replace(/&(amp|lt|gt|quot|#39|#x27);/g,function(t){return H[t]||t})}};function Y(t){let e=String(t).split(".");if(4!==e.length)return!1;for(let t=0;t<e.length;t++){if(!/^\d{1,3}$/.test(e[t]))return!1;if(+e[t]>255)return!1}return!0}function q(t){return t.every(function(t){return/^[0-9a-fA-F]{1,4}$/.test(t)})}function Z(t){let e=String(t);if(!e)return!1;let r=e.indexOf("::");if(-1===r){let t=e.split(":");return 8===t.length&&q(t)}if(-1!==e.indexOf("::",r+2))return!1;let n=e.substring(0,r),i=e.substring(r+2),o=n?n.split(":"):[],u=i?i.split(":"):[];return!(o.length+u.length>7)&&(q(o)&&q(u))}const J={isMobile:function(t){return/^1[3-9]\d{9}$/.test(String(t))},isEmail:function(t){return/^[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}$/.test(String(t))},isIdCard:function(t){let e,r,n,i=String(t);if(!/^\d{15}$/.test(i)&&!/^\d{17}[\dXx]$/.test(i))return!1;if(15===i.length?(e=+i.substring(6,8)+1900,r=+i.substring(8,10),n=+i.substring(10,12)):(e=+i.substring(6,10),r=+i.substring(10,12),n=+i.substring(12,14)),!s(e,r,n))return!1;if(15===i.length)return!0;let o=[7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2],u=0;for(let t=0;t<17;t++)u+=+i.charAt(t)*o[t];return"10X98765432".charAt(u%11)===i.charAt(17).toUpperCase()},isUrl:function(t){return/^((https?|ftp):\/\/)([\w-]+\.)*[\w-]+(:\d+)?(\/[\w\-./?%&=#+~:@!$'()*,;]*)?$/.test(String(t))},isIPv4:Y,isIPv6:Z,isIp:function(t){return Y(t)||Z(t)},isBankCard:function(t){let e=String(t).replace(/\s/g,"");if(!/^\d{12,19}$/.test(e))return!1;let r=0;for(let t=0;t<e.length;t++){let n=+e.charAt(e.length-1-t);t%2==1&&(n*=2,n>9&&(n-=9)),r+=n}return r%10==0},isInteger:function(t){return"number"==typeof t?isFinite(t)&&Math.floor(t)===t:/^[+-]?\d+$/.test(String(t).trim())},isDecimal:function(t){return/^[+-]?(\d+\.?\d*|\.\d+)$/.test(String(t))},isChinese:function(t){return/^[\u4E00-\u9FA5]+$/.test(String(t))},isPostCode:function(t){return/^[1-9]\d{5}$/.test(String(t))}};function V(t){return Array.isArray(t)?t.map(String):String(t).replace(/\[(?:"([^"]*)"|'([^']*)'|(\d+)|(\w+))\]/g,function(t,e,r,n,i){return"."+(e||r||n||i)}).split(".").filter(function(t){return""!==t})}function W(t,e){if("object"!=typeof t||null===t)return t;if((e=e||new WeakMap).has(t))return e.get(t);if(c(t))return new Date(t.getTime());if(h(t)){let e=new RegExp(t.source,t.flags);return e.lastIndex=t.lastIndex,e}if(function(t){return f(t,"ArrayBuffer")}(t))return t.slice(0);let r;if(p(t))return r=new Map,e.set(t,r),t.forEach(function(t,n){r.set(W(n,e),W(t,e))}),r;if(g(t))return r=new Set,e.set(t,r),t.forEach(function(t){r.add(W(t,e))}),r;if(Array.isArray(t)){r=[],e.set(t,r);for(let n=0;n<t.length;n++)r[n]=W(t[n],e);return r}return d(t)?(r=Object.create(Object.getPrototypeOf(t)),e.set(t,r),Object.keys(t).forEach(function(n){r[n]=W(t[n],e)}),r):t}function Q(t,e,r){if(Object.is(t,e))return!0;if("object"!=typeof t||"object"!=typeof e||null===t||null===e)return!1;for(let n=0;n<r.length;n++)if(r[n][0]===t&&r[n][1]===e)return!0;if(r.push([t,e]),c(t)||c(e))return c(t)&&c(e)&&t.getTime()===e.getTime();if(h(t)||h(e))return h(t)&&h(e)&&t.toString()===e.toString();if(p(t)||p(e)){if(!p(t)||!p(e)||t.size!==e.size)return!1;let n=!0;return t.forEach(function(t,i){e.has(i)&&Q(t,e.get(i),r)||(n=!1)}),n}if(g(t)||g(e)){if(!g(t)||!g(e)||t.size!==e.size)return!1;let r=!0;return t.forEach(function(t){e.has(t)||(r=!1)}),r}if(Array.isArray(t)!==Array.isArray(e))return!1;let n=Object.keys(t),i=Object.keys(e);if(n.length!==i.length)return!1;for(let i=0;i<n.length;i++){if(!Object.prototype.hasOwnProperty.call(e,n[i]))return!1;if(!Q(t[n[i]],e[n[i]],r))return!1}return!0}function X(t,e,r){return Object.keys(e).forEach(function(n){let i=e[n],o=t[n];d(i)&&d(o)?t[n]=X(W(o),i,r):Array.isArray(i)&&Array.isArray(o)&&"concat"===r.array?t[n]=o.concat(W(i)):t[n]=W(i)}),t}const G={deepClone:W,deepMerge:function(t,e,r){return r=r||{},X(W(void 0===t?{}:t),e||{},r)},get:function(t,e,r){let n=V(e),i=t;for(let t=0;t<n.length;t++){if(m(i))return r;i=i[n[t]]}return void 0===i?r:i},set:function(t,e,r){if("object"!=typeof t||null===t)throw new TypeError("set 的目标必须是对象或数组");let n=V(e),i=t;for(let t=0;t<n.length-1;t++){let e=n[t];"object"==typeof i[e]&&null!==i[e]||(i[e]=/^\d+$/.test(n[t+1])?[]:{}),i=i[e]}return i[n[n.length-1]]=r,t},toPath:V,pick:function(t,e){e=Array.isArray(e)?e:Array.prototype.slice.call(arguments,1);let r={};return e.forEach(function(e){null!=t&&e in Object(t)&&(r[e]=t[e])}),r},omit:function(t,e){e=Array.isArray(e)?e:Array.prototype.slice.call(arguments,1);let r={},n=e.map(String);return Object.keys(Object(t)).forEach(function(e){-1===n.indexOf(e)&&(r[e]=t[e])}),r},isEmpty:function(t){return!!m(t)||("string"==typeof t||Array.isArray(t)?0===t.length:p(t)||g(t)?0===t.size:!!d(t)&&0===Object.keys(t).length)},isPlainObject:d,equal:function(t,e){return Q(t,e,[])}};function K(t){return"function"==typeof t?t:"string"==typeof t||"number"==typeof t?function(e){return null==e?void 0:e[t]}:function(t){return t}}function tt(t){if("function"==typeof t)return{fn:t,desc:!1};if(Array.isArray(t))return{fn:K(t[0]),desc:"desc"===String(t[1]).toLowerCase()};let e=String(t);return"-"===e.charAt(0)?{fn:K(e.substring(1)),desc:!0}:{fn:K(e),desc:!1}}function et(t,e){let r=null==t,n=null==e;return r&&n?0:r?1:n?-1:(t instanceof Date&&(t=t.getTime()),e instanceof Date&&(e=e.getTime()),"number"==typeof t&&"number"==typeof e?t-e:(t=String(t))<(e=String(e))?-1:t>e?1:0)}const rt={unique:function(t){return Array.from(new Set(t))},uniqueBy:function(t,e){let r=K(e),n=new Set,i=[];return t.forEach(function(t){let e=r(t);n.has(e)||(n.add(e),i.push(t))}),i},groupBy:function(t,e){let r=K(e),n={};return t.forEach(function(t){let e=r(t);Object.prototype.hasOwnProperty.call(n,e)||(n[e]=[]),n[e].push(t)}),n},sortBy:function(t,e){let r=(Array.isArray(e)?e:Array.prototype.slice.call(arguments,1)).map(tt);return t.slice().sort(function(t,e){for(let n=0;n<r.length;n++){let i=et(r[n].fn(t),r[n].fn(e));if(0!==i)return r[n].desc?-i:i}return 0})},flatten:function t(e,r){r=void 0===r?1/0:r;let n=[];return e.forEach(function(e){Array.isArray(e)&&r>0?n=n.concat(t(e,r-1)):n.push(e)}),n},chunk:function(t,e){if(!(e>0))throw new TypeError("chunk 的 size 必须大于 0");let r=[];for(let n=0;n<t.length;n+=e)r.push(t.slice(n,n+e));return r},compact:function(t){return t.filter(Boolean)},shuffle:function(t){let e=t.slice();for(let t=e.length-1;t>0;t--){let r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e},range:function(t,e,r){if(void 0===e&&(e=t,t=0),0===(r=void 0===r?t<=e?1:-1:r))throw new TypeError("range 的 step 不能为 0");let n=[];if(r>0)for(let i=t;i<e;i+=r)n.push(i);else for(let i=t;i>e;i+=r)n.push(i);return n}};function nt(t){let e=String(t).replace(/\+/g," ");try{return decodeURIComponent(e)}catch(t){return e}}function it(t){return encodeURIComponent(String(t)).replace(/%5B/g,"[").replace(/%5D/g,"]")}function ot(t){let e={},r=String(null==t?"":t),n=r.indexOf("?");-1!==n&&(r=r.substring(n+1));let i=r.indexOf("#");return-1!==i&&(r=r.substring(0,i)),r?(r.split("&").forEach(function(t){if(!t)return;let r=t.indexOf("="),n=-1===r?t:t.substring(0,r),i=-1===r?"":t.substring(r+1),o=nt(n);if(!o)return;let u=function(t){let e=/\[\]$/.test(t);return{tokens:(e?t.substring(0,t.length-2):t).split(/\[|\]/).filter(function(t){return""!==t}),arrayFlag:e}}(o);u.tokens.length&&function(t,e,r,n){let i=t;for(let t=0;t<e.length-1;t++){let r=e[t];"object"==typeof i[r]&&null!==i[r]||(i[r]=/^\d+$/.test(e[t+1])?[]:{}),i=i[r]}let o=e[e.length-1];if(n)return Array.isArray(i[o])||(i[o]=[]),void i[o].push(r);void 0===i[o]?i[o]=r:Array.isArray(i[o])?i[o].push(r):i[o]=[i[o],r]}(e,u.tokens,nt(i),u.arrayFlag)}),e):e}const ut={parseQuery:ot,stringifyQuery:function(t){let e=[];function r(t,n){void 0!==t&&(null!==t?Array.isArray(t)?t.forEach(function(t){void 0!==t&&r(t,n)}):"object"!=typeof t||t instanceof Date?e.push(it(n)+"="+it(t)):Object.keys(t).forEach(function(e){r(t[e],n+"["+e+"]")}):e.push(it(n)+"="))}return t&&"object"==typeof t&&Object.keys(t).forEach(function(e){r(t[e],e)}),e.join("&")},parseUrl:function(t){let e=/^([a-zA-Z][a-zA-Z0-9+.\-]*:)?(?:\/\/([^/?#]*))?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(String(t));if(!e)throw new TypeError("非法的 URL:"+t);let r=e[1]?e[1].substring(0,e[1].length-1).toLowerCase():"",n=e[2]||"",i="",o="",u=n.lastIndexOf("@");if(-1!==u){let t=n.substring(0,u);n=n.substring(u+1);let e=t.indexOf(":");-1===e?i=t:(i=t.substring(0,e),o=t.substring(e+1))}let s=n,a="",f=n.lastIndexOf(":");-1!==f&&f>n.lastIndexOf("]")&&(s=n.substring(0,f),a=n.substring(f+1));let l=e[4]?e[4].substring(1):"",c=e[5]?e[5].substring(1):"",h={protocol:r,host:n,hostname:s,port:a,username:i,password:o,path:e[3]||"",query:l,hash:c};return Object.defineProperty(h,"params",{value:ot(l),enumerable:!1}),h}},st="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";function at(){return"undefined"!=typeof globalThis&&globalThis.crypto&&"function"==typeof globalThis.crypto.getRandomValues?globalThis.crypto:null}function ft(t){let e=new Array(t),r=at();if(r){let n=new Uint8Array(t);r.getRandomValues(n);for(let r=0;r<t;r++)e[r]=n[r]}else for(let r=0;r<t;r++)e[r]=Math.floor(256*Math.random());return e}const lt={uuid:function(){let t=ft(16);t[6]=15&t[6]|64,t[8]=63&t[8]|128;let e=t.map(function(t){return(t+256).toString(16).substring(1)}).join("");return e.substring(0,8)+"-"+e.substring(8,12)+"-"+e.substring(12,16)+"-"+e.substring(16,20)+"-"+e.substring(20)},nanoid:function(t,e){if(e=e||st,!((t=void 0===t?21:t)>0))throw new TypeError("nanoid 的 size 必须大于 0");if(e.length<2)throw new TypeError("nanoid 的 alphabet 至少需要 2 个字符");let r=ft(t),n="";for(let i=0;i<t;i++)n+=e.charAt(r[i]%e.length);return n},randomInt:function(t,e){if(void 0===e&&(e=t,t=0),t=Math.ceil(t),(e=Math.floor(e))<t)throw new TypeError("randomInt 的 max 不能小于 min");return t+Math.floor(Math.random()*(e-t+1))},randomString:function(t,e){if(e=e||st,!((t=void 0===t?8:t)>0))throw new TypeError("randomString 的 size 必须大于 0");let r=ft(t),n="";for(let i=0;i<t;i++)n+=e.charAt(r[i]%e.length);return n},isSecure:function(){return null!==at()}};function ct(t,e,r){return t<e?e:t>r?r:t}function ht(t){let e=Math.round(ct(t,0,255)).toString(16);return 1===e.length?"0"+e:e}function pt(t){let e=function(t){let e=String(null==t?"":t).trim().replace(/^#/,"");if(/^[0-9a-fA-F]{3}$/.test(e)&&(e=e.split("").map(function(t){return t+t}).join("")),/^[0-9a-fA-F]{4}$/.test(e)&&(e=e.split("").map(function(t){return t+t}).join("")),!/^[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$/.test(e))throw new TypeError("非法的颜色值:"+t);return"#"+e.toLowerCase()}(t).substring(1),r={r:parseInt(e.substring(0,2),16),g:parseInt(e.substring(2,4),16),b:parseInt(e.substring(4,6),16),a:1};return 8===e.length&&(r.a=Math.round(parseInt(e.substring(6,8),16)/255*100)/100),r}function gt(t){if(!t||"object"!=typeof t)throw new TypeError("rgb2hex 需要一个 { r, g, b } 对象");let e=void 0===t.a?1:ct(t.a,0,1),r="#"+ht(t.r)+ht(t.g)+ht(t.b);return e<1?r+ht(255*e):r}function yt(t,e,r){r=void 0===r?.5:ct(r,0,1);let n=pt(t),i=pt(e);return gt({r:Math.round(n.r*(1-r)+i.r*r),g:Math.round(n.g*(1-r)+i.g*r),b:Math.round(n.b*(1-r)+i.b*r)})}const dt={hex2rgb:pt,rgb2hex:gt,rgb2hsl:function(t){let e=ct(t.r,0,255)/255,r=ct(t.g,0,255)/255,n=ct(t.b,0,255)/255,i=Math.max(e,r,n),o=Math.min(e,r,n),u=i-o,s=(i+o)/2,a=0,f=0;if(0!==u){switch(f=u/(1-Math.abs(2*s-1)),i){case e:a=(r-n)/u%6;break;case r:a=(n-e)/u+2;break;default:a=(e-r)/u+4}a*=60,a<0&&(a+=360)}return{h:Math.round(100*a)/100,s:Math.round(1e4*f)/100,l:Math.round(1e4*s)/100}},hsl2rgb:function(t){let e,r=(t.h%360+360)%360,n=ct(t.s,0,100)/100,i=ct(t.l,0,100)/100,o=(1-Math.abs(2*i-1))*n,u=o*(1-Math.abs(r/60%2-1)),s=i-o/2;return e=r<60?[o,u,0]:r<120?[u,o,0]:r<180?[0,o,u]:r<240?[0,u,o]:r<300?[u,0,o]:[o,0,u],{r:Math.round(255*(e[0]+s)),g:Math.round(255*(e[1]+s)),b:Math.round(255*(e[2]+s))}},mix:yt,lighten:function(t,e){return yt(t,"#ffffff",void 0===e?.3:e)},darken:function(t,e){return yt(t,"#000000",void 0===e?.3:e)},contrast:function(t){let e=pt(t),r=function(t){let e=t/255;return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)};return.2126*r(e.r)+.7152*r(e.g)+.0722*r(e.b)>.5?"#000000":"#ffffff"},toRgba:function(t,e){let r=pt(t);return e=void 0===e?1:ct(e,0,1),"rgba("+r.r+", "+r.g+", "+r.b+", "+e+")"}};function mt(){let t=new Map;return{getItem:function(e){return t.has(e)?t.get(e):null},setItem:function(e,r){t.set(e,r)},removeItem:function(e){t.delete(e)},keys:function(){return Array.from(t.keys())}}}function bt(t){try{if("undefined"!=typeof globalThis&&globalThis[t]){let e=globalThis[t],r="__corejs_probe__";return e.setItem(r,"1"),e.removeItem(r),function(t){return{getItem:function(e){return t.getItem(e)},setItem:function(e,r){t.setItem(e,r)},removeItem:function(e){t.removeItem(e)},keys:function(){let e=[];for(let r=0;r<t.length;r++)e.push(t.key(r));return e}}}(e)}}catch(t){}return null}function wt(t){if(t&&"object"==typeof t&&"function"==typeof t.getItem&&"function"==typeof t.setItem&&"function"==typeof t.removeItem)return t;if("memory"===t)return mt();if("local"===t){let t=bt("localStorage");return t||mt()}if("session"===t){let t=bt("sessionStorage");return t||mt()}return bt("localStorage")||bt("sessionStorage")||mt()}function vt(t){if(null==t||0===t)return 0;if(t instanceof Date){let e=t.getTime();if(!isFinite(e))throw new TypeError("非法的过期时间");return e}if("number"==typeof t){if(!isFinite(t)||t<0)throw new TypeError("非法的过期时间:"+t);return t<1e11?Date.now()+t:t}throw new TypeError("非法的过期时间:"+t)}function Mt(t,e){"object"==typeof t&&null!==t&&void 0===e&&(e=t,t=void 0),e=e||{},this.namespace=t||"corejs",Object.defineProperty(this,"_driver",{value:wt(e.driver),enumerable:!1})}Mt.prototype._key=function(t){return this.namespace+":"+t},function(t){t.prototype.set=function(t,e,r){let n={v:e,e:vt(r)};return this._driver.setItem(this._key(t),JSON.stringify(n)),this},t.prototype.get=function(t,e){let r,n=this._driver.getItem(this._key(t));if(null==n)return e;try{r=JSON.parse(n)}catch(r){return this.remove(t),e}return r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"v")?r.e&&r.e<=Date.now()?(this.remove(t),e):r.v:(this.remove(t),e)},t.prototype.has=function(t){let e,r=this._driver.getItem(this._key(t));if(null==r)return!1;try{e=JSON.parse(r)}catch(e){return this.remove(t),!1}return e&&"object"==typeof e&&!(e.e&&e.e<=Date.now())||(this.remove(t),!1)},t.prototype.remove=function(t){return this._driver.removeItem(this._key(t)),this},t.prototype.keys=function(){let t=this.namespace+":",e=[];this._driver.keys().forEach(function(r){0===r.indexOf(t)&&e.push(r.substring(t.length))});let r=this;return e.filter(function(t){return r.has(t)})},t.prototype.size=function(){return this.keys().length},t.prototype.clear=function(){let t=this;return this.keys().forEach(function(e){t.remove(e)}),this}}(Mt),t.Array=rt,t.Cache=Mt,t.Color=dt,t.Digits=$,t.Id=lt,t.Object=G,t.Query=ut,t.String=N,t.Time=w,t.Validate=J});
package/package.json CHANGED
@@ -1,34 +1,63 @@
1
- {
2
- "name": "@oipage/core.js",
3
- "version": "1.0.0",
4
- "description": "包括日期、时间、浮点运算等常用的一些业务API",
5
- "main": "./dist/core.js",
6
- "typings": "./types/index.d.ts",
7
- "scripts": {
8
- "start": "npm install && npm run dev",
9
- "dev": "oipage-cli run \"rollup --config ./rollup.config.js -w\" \"oipage-cli serve -p 20000\"",
10
- "build": "rollup --config ./rollup.config.js && terser ./dist/core.js --compress --mangle --output ./dist/core.min.js"
11
- },
12
- "repository": {
13
- "type": "git",
14
- "url": "git+https://github.com/oi-contrib/oipage-corejs.git"
15
- },
16
- "author": {
17
- "name": "zxl20070701",
18
- "url": "https://zxl20070701.github.io/notebook/home.html"
19
- },
20
- "keywords": [
21
- "oipage",
22
- "core",
23
- "javascript"
24
- ],
25
- "license": "MIT",
26
- "devDependencies": {
27
- "@rollup/plugin-node-resolve": "^16.0.1",
28
- "rollup": "^4.6.1",
29
- "terser": "^5.17.1"
30
- },
31
- "dependencies": {
32
- "oipage": "^1.4.1"
33
- }
34
- }
1
+ {
2
+ "name": "@oipage/core.js",
3
+ "version": "1.1.0-alpha.0",
4
+ "description": "包括日期、时间、浮点运算、字符串、校验、缓存等常用的一些业务API",
5
+ "main": "./dist/core.js",
6
+ "module": "./dist/core.esm.js",
7
+ "typings": "./types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./types/index.d.ts",
11
+ "import": "./dist/core.esm.js",
12
+ "require": "./dist/core.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "sideEffects": false,
17
+ "files": [
18
+ "dist",
19
+ "types",
20
+ "src",
21
+ "CHANGELOG",
22
+ "LICENSE",
23
+ "README.md"
24
+ ],
25
+ "scripts": {
26
+ "start": "npm install && npm run dev",
27
+ "dev": "oipage-cli run \"rollup --config ./rollup.config.js -w\" \"oipage-cli serve -p 20000 --open ./test/\"",
28
+ "build": "rollup --config ./rollup.config.js && terser ./dist/core.js --compress --mangle --output ./dist/core.min.js",
29
+ "test": "npm run build && node ./test/unit/index.js",
30
+ "typecheck": "tsc --noEmit",
31
+ "docs:build": "oipage-cli disk --copy ./node_modules/@oipage/shader/dist/shader.min.js ./docs/assets/shader.min.js -f",
32
+ "docs:dev": "oipage-cli serve -p 20001 --open ./docs/index.html --website false"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/oi-contrib/oipage-corejs.git"
37
+ },
38
+ "author": {
39
+ "name": "zxl20070701",
40
+ "url": "https://zxl20070701.github.io/notebook/home.html"
41
+ },
42
+ "keywords": [
43
+ "oipage",
44
+ "core",
45
+ "date",
46
+ "time",
47
+ "bigint",
48
+ "decimal",
49
+ "validate",
50
+ "cache",
51
+ "utils"
52
+ ],
53
+ "license": "MIT",
54
+ "devDependencies": {
55
+ "@oipage/cli": "^0.2.1",
56
+ "@oipage/shader": "^0.1.0",
57
+ "@oipage/testjs": "^0.1.0",
58
+ "@rollup/plugin-node-resolve": "^16.0.1",
59
+ "rollup": "^4.6.1",
60
+ "terser": "^5.17.1",
61
+ "typescript": "^5.9.3"
62
+ }
63
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Array 分组
3
+ */
4
+ import { toIteratee } from "./tool.js"
5
+
6
+ /**
7
+ * 分组,返回以分组键为属性的普通对象
8
+ */
9
+ export function groupBy(list, iteratee) {
10
+ let fn = toIteratee(iteratee)
11
+ let result = {}
12
+
13
+ list.forEach(function (item) {
14
+ let key = fn(item)
15
+ if (!Object.prototype.hasOwnProperty.call(result, key)) result[key] = []
16
+ result[key].push(item)
17
+ })
18
+
19
+ return result
20
+ }
21
+
22
+ export function normalizeKey(key) {
23
+ if (typeof key === "function") return { fn: key, desc: false }
24
+
25
+ if (Array.isArray(key)) {
26
+ return { fn: toIteratee(key[0]), desc: String(key[1]).toLowerCase() === "desc" }
27
+ }
28
+
29
+ let str = String(key)
30
+ if (str.charAt(0) === "-") {
31
+ return { fn: toIteratee(str.substring(1)), desc: true }
32
+ }
33
+
34
+ return { fn: toIteratee(str), desc: false }
35
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Array 对外入口
3
+ */
4
+ import { groupBy } from "./group.js"
5
+ import { chunk, compact, flatten, range, shuffle } from "./list.js"
6
+ import { sortBy } from "./sort.js"
7
+ import { unique, uniqueBy } from "./unique.js"
8
+
9
+ const ArrayUtil = {
10
+ unique: unique,
11
+ uniqueBy: uniqueBy,
12
+ groupBy: groupBy,
13
+ sortBy: sortBy,
14
+ flatten: flatten,
15
+ chunk: chunk,
16
+ compact: compact,
17
+ shuffle: shuffle,
18
+ range: range
19
+ }
20
+
21
+ export { ArrayUtil as Array }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Array 结构处理
3
+ */
4
+
5
+ /**
6
+ * 拍平数组
7
+ *
8
+ * @param {number} depth 拍平深度,默认 Infinity
9
+ */
10
+ export function flatten(list, depth) {
11
+ depth = depth === undefined ? Infinity : depth
12
+
13
+ let result = []
14
+ list.forEach(function (item) {
15
+ if (Array.isArray(item) && depth > 0) {
16
+ result = result.concat(flatten(item, depth - 1))
17
+ } else {
18
+ result.push(item)
19
+ }
20
+ })
21
+
22
+ return result
23
+ }
24
+
25
+ /**
26
+ * 按长度切分
27
+ */
28
+ export function chunk(list, size) {
29
+ if (!(size > 0)) throw new TypeError("chunk 的 size 必须大于 0")
30
+
31
+ let result = []
32
+ for (let i = 0; i < list.length; i += size) {
33
+ result.push(list.slice(i, i + size))
34
+ }
35
+
36
+ return result
37
+ }
38
+
39
+ /**
40
+ * 去掉 falsey 值(false、0、""、null、undefined、NaN)
41
+ */
42
+ export function compact(list) {
43
+ return list.filter(Boolean)
44
+ }
45
+
46
+ /**
47
+ * 随机打乱(Fisher-Yates)
48
+ */
49
+ export function shuffle(list) {
50
+ let result = list.slice()
51
+ for (let i = result.length - 1; i > 0; i--) {
52
+ let index = Math.floor(Math.random() * (i + 1))
53
+ let temp = result[i]
54
+ result[i] = result[index]
55
+ result[index] = temp
56
+ }
57
+ return result
58
+ }
59
+
60
+ /**
61
+ * 生成数字序列,左闭右开
62
+ */
63
+ export function range(start, end, step) {
64
+ if (end === undefined) {
65
+ end = start
66
+ start = 0
67
+ }
68
+ step = step === undefined ? (start <= end ? 1 : -1) : step
69
+ if (step === 0) throw new TypeError("range 的 step 不能为 0")
70
+
71
+ let result = []
72
+ if (step > 0) {
73
+ for (let i = start; i < end; i += step) result.push(i)
74
+ } else {
75
+ for (let i = start; i > end; i += step) result.push(i)
76
+ }
77
+
78
+ return result
79
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Array 排序
3
+ */
4
+ import { normalizeKey } from "./group.js"
5
+
6
+ function compareValue(a, b) {
7
+ let aEmpty = a === null || a === undefined
8
+ let bEmpty = b === null || b === undefined
9
+
10
+ if (aEmpty && bEmpty) return 0
11
+ if (aEmpty) return 1 // 空值统一排后面
12
+ if (bEmpty) return -1
13
+
14
+ if (a instanceof Date) a = a.getTime()
15
+ if (b instanceof Date) b = b.getTime()
16
+
17
+ if (typeof a === "number" && typeof b === "number") return a - b
18
+
19
+ a = String(a)
20
+ b = String(b)
21
+
22
+ return a < b ? -1 : (a > b ? 1 : 0)
23
+ }
24
+
25
+ /**
26
+ * 多字段排序,返回新数组
27
+ *
28
+ * @param {Array} keys 排序键,字符串("-" 前缀表示倒序)、函数,或 [键, "desc"]
29
+ */
30
+ export function sortBy(list, keys) {
31
+ let rules = (Array.isArray(keys) ? keys : Array.prototype.slice.call(arguments, 1)).map(normalizeKey)
32
+
33
+ return list.slice().sort(function (a, b) {
34
+ for (let i = 0; i < rules.length; i++) {
35
+ let result = compareValue(rules[i].fn(a), rules[i].fn(b))
36
+ if (result !== 0) return rules[i].desc ? -result : result
37
+ }
38
+ return 0
39
+ })
40
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Array 内部工具
3
+ */
4
+
5
+ /**
6
+ * Array:数组处理
7
+ * 全部返回新数组,不修改入参
8
+ */
9
+
10
+ export function toIteratee(iteratee) {
11
+ if (typeof iteratee === "function") return iteratee
12
+ if (typeof iteratee === "string" || typeof iteratee === "number") {
13
+ return function (item) {
14
+ return item === null || item === undefined ? undefined : item[iteratee]
15
+ }
16
+ }
17
+ return function (item) {
18
+ return item
19
+ }
20
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Array 去重
3
+ */
4
+ import { toIteratee } from "./tool.js"
5
+
6
+ /**
7
+ * 去重,使用 SameValueZero 语义(NaN 会被正确去重,对象按引用比较)
8
+ */
9
+ export function unique(list) {
10
+ return Array.from(new Set(list))
11
+ }
12
+
13
+ /**
14
+ * 按字段或函数去重,保留第一次出现的元素
15
+ */
16
+ export function uniqueBy(list, iteratee) {
17
+ let fn = toIteratee(iteratee)
18
+ let seen = new Set()
19
+ let result = []
20
+
21
+ list.forEach(function (item) {
22
+ let key = fn(item)
23
+ if (!seen.has(key)) {
24
+ seen.add(key)
25
+ result.push(item)
26
+ }
27
+ })
28
+
29
+ return result
30
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Cache 存储驱动
3
+ */
4
+
5
+ /**
6
+ * Cache:带过期时间的键值存储
7
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
8
+ */
9
+
10
+ export function createStorageDriver(storage) {
11
+ return {
12
+ getItem: function (key) {
13
+ return storage.getItem(key)
14
+ },
15
+ setItem: function (key, value) {
16
+ storage.setItem(key, value)
17
+ },
18
+ removeItem: function (key) {
19
+ storage.removeItem(key)
20
+ },
21
+ keys: function () {
22
+ let result = []
23
+ for (let i = 0; i < storage.length; i++) result.push(storage.key(i))
24
+ return result
25
+ }
26
+ }
27
+ }
28
+
29
+ export function createMemoryDriver() {
30
+ let store = new Map()
31
+
32
+ return {
33
+ getItem: function (key) {
34
+ return store.has(key) ? store.get(key) : null
35
+ },
36
+ setItem: function (key, value) {
37
+ store.set(key, value)
38
+ },
39
+ removeItem: function (key) {
40
+ store.delete(key)
41
+ },
42
+ keys: function () {
43
+ return Array.from(store.keys())
44
+ }
45
+ }
46
+ }
47
+
48
+ export function tryStorage(name) {
49
+ try {
50
+ if (typeof globalThis !== "undefined" && globalThis[name]) {
51
+ let storage = globalThis[name]
52
+ let probe = "__corejs_probe__"
53
+ storage.setItem(probe, "1")
54
+ storage.removeItem(probe)
55
+ return createStorageDriver(storage)
56
+ }
57
+ } catch (error) {
58
+ // 隐私模式等场景写入会抛错,直接降级
59
+ }
60
+ return null
61
+ }
62
+
63
+ export function resolveDriver(driver) {
64
+ if (driver && typeof driver === "object"
65
+ && typeof driver.getItem === "function"
66
+ && typeof driver.setItem === "function"
67
+ && typeof driver.removeItem === "function") {
68
+ return driver
69
+ }
70
+
71
+ if (driver === "memory") return createMemoryDriver()
72
+
73
+ if (driver === "local") {
74
+ let local = tryStorage("localStorage")
75
+ if (local) return local
76
+ return createMemoryDriver()
77
+ }
78
+
79
+ if (driver === "session") {
80
+ let session = tryStorage("sessionStorage")
81
+ if (session) return session
82
+ return createMemoryDriver()
83
+ }
84
+
85
+ return tryStorage("localStorage") || tryStorage("sessionStorage") || createMemoryDriver()
86
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Cache 过期时间
3
+ */
4
+
5
+ export function toExpire(expire) {
6
+ if (expire === undefined || expire === null || expire === 0) return 0
7
+
8
+ if (expire instanceof Date) {
9
+ let stamp = expire.getTime()
10
+ if (!isFinite(stamp)) throw new TypeError("非法的过期时间")
11
+ return stamp
12
+ }
13
+
14
+ if (typeof expire === "number") {
15
+ if (!isFinite(expire) || expire < 0) throw new TypeError("非法的过期时间:" + expire)
16
+ // 小于 1e11 的按“相对毫秒”处理,否则按“绝对时间戳”处理
17
+ return expire < 100000000000 ? Date.now() + expire : expire
18
+ }
19
+
20
+ throw new TypeError("非法的过期时间:" + expire)
21
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Cache:带过期时间的键值存储
3
+ * 默认优先用 localStorage,其次 sessionStorage,都没有(如 Node 环境)时退回内存
4
+ */
5
+ import { resolveDriver } from "./driver"
6
+ import { useStore } from "./store"
7
+
8
+ /**
9
+ * @param {string} namespace 命名空间,默认 corejs
10
+ * @param {object} options
11
+ * @param {string|object} options.driver local、session、memory,或自定义 { getItem, setItem, removeItem }
12
+ */
13
+ export function Cache(namespace, options) {
14
+ if (typeof namespace === "object" && namespace !== null && options === undefined) {
15
+ options = namespace
16
+ namespace = undefined
17
+ }
18
+
19
+ options = options || {}
20
+
21
+ this.namespace = namespace || "corejs"
22
+
23
+ Object.defineProperty(this, "_driver", {
24
+ value: resolveDriver(options.driver),
25
+ enumerable: false
26
+ })
27
+ }
28
+
29
+ Cache.prototype._key = function (key) {
30
+ return this.namespace + ":" + key
31
+ }
32
+
33
+ useStore(Cache)
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Cache 读写
3
+ */
4
+ import { toExpire } from "./expire"
5
+
6
+ export function useStore(Cache) {
7
+ /**
8
+ * 写入缓存
9
+ *
10
+ * @param {string} key 键
11
+ * @param {*} value 值,会被 JSON 序列化
12
+ * @param {number|Date} expire 过期时间:毫秒(相对)或时间戳 / Date(绝对),不传表示不过期
13
+ */
14
+ Cache.prototype.set = function (key, value, expire) {
15
+ let data = {
16
+ v: value,
17
+ e: toExpire(expire)
18
+ }
19
+
20
+ this._driver.setItem(this._key(key), JSON.stringify(data))
21
+ return this
22
+ }
23
+
24
+ /**
25
+ * 读取缓存,过期或不存在时返回 defaultValue
26
+ */
27
+ Cache.prototype.get = function (key, defaultValue) {
28
+ let str = this._driver.getItem(this._key(key))
29
+ if (str === null || str === undefined) return defaultValue
30
+
31
+ let data
32
+ try {
33
+ data = JSON.parse(str)
34
+ } catch (error) {
35
+ this.remove(key)
36
+ return defaultValue
37
+ }
38
+
39
+ if (!data || typeof data !== "object" || !Object.prototype.hasOwnProperty.call(data, "v")) {
40
+ this.remove(key)
41
+ return defaultValue
42
+ }
43
+
44
+ if (data.e && data.e <= Date.now()) {
45
+ this.remove(key)
46
+ return defaultValue
47
+ }
48
+
49
+ return data.v
50
+ }
51
+
52
+ Cache.prototype.has = function (key) {
53
+ let str = this._driver.getItem(this._key(key))
54
+ if (str === null || str === undefined) return false
55
+
56
+ let data
57
+ try {
58
+ data = JSON.parse(str)
59
+ } catch (error) {
60
+ this.remove(key)
61
+ return false
62
+ }
63
+
64
+ if (!data || typeof data !== "object") {
65
+ this.remove(key)
66
+ return false
67
+ }
68
+
69
+ if (data.e && data.e <= Date.now()) {
70
+ this.remove(key)
71
+ return false
72
+ }
73
+
74
+ return true
75
+ }
76
+
77
+ Cache.prototype.remove = function (key) {
78
+ this._driver.removeItem(this._key(key))
79
+ return this
80
+ }
81
+
82
+ /**
83
+ * 当前命名空间下仍然有效的键
84
+ */
85
+ Cache.prototype.keys = function () {
86
+ let prefix = this.namespace + ":"
87
+ let result = []
88
+
89
+ this._driver.keys().forEach(function (fullKey) {
90
+ if (fullKey.indexOf(prefix) === 0) result.push(fullKey.substring(prefix.length))
91
+ })
92
+
93
+ let self = this
94
+ return result.filter(function (key) {
95
+ return self.has(key)
96
+ })
97
+ }
98
+
99
+ Cache.prototype.size = function () {
100
+ return this.keys().length
101
+ }
102
+
103
+ /**
104
+ * 清空当前命名空间(不会影响其它命名空间的数据)
105
+ */
106
+ Cache.prototype.clear = function () {
107
+ let self = this
108
+ this.keys().forEach(function (key) {
109
+ self.remove(key)
110
+ })
111
+ return this
112
+ }
113
+ }