devix 0.0.12 → 0.0.14

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.
package/README.md CHANGED
@@ -17,3 +17,20 @@ import { [[ModuleName]] } from 'devix'
17
17
  // Using CommonJS
18
18
  var { [[ModuleName]] } = require('devix')
19
19
  ```
20
+
21
+ ## API
22
+
23
+ - bubblingSort
24
+ - compose
25
+ - currying
26
+ - debounce
27
+ - deepClone
28
+ - formatTimer
29
+ - insertStr
30
+ - isType
31
+ - localCache
32
+ - sessionCache
33
+ - setTimer
34
+ - shallowClone
35
+ - stringCase
36
+ - throttle
@@ -0,0 +1,5 @@
1
+ "use strict";const t={string:t=>"string"==typeof t,number:t=>"number"==typeof t,boolean:t=>"boolean"==typeof t,null:t=>null===t,undefined:t=>void 0===t,symbol:t=>"symbol"==typeof t,bigint:t=>"bigint"==typeof t,object:t=>null!==t&&"object"==typeof t,array:t=>Array.isArray(t),function:t=>"function"==typeof t,set:t=>t instanceof Set,map:t=>t instanceof Map,date:t=>t instanceof Date,regexp:t=>t instanceof RegExp},e=(e,n)=>t[e]?.(n)||!1;var n;!function(t){t[t.Local=0]="Local",t[t.Session=1]="Session"}(n||(n={}));class o{constructor(t){this.storage=t===n.Local?localStorage:sessionStorage}getCache(t){const e=this.storage.getItem(t);return e?JSON.parse(e):null}setCache(t,e){this.storage.setItem(t,JSON.stringify(e))}updateCache(t,n,o){const r=this.getCache(t);e("object",r)&&(r[n]=o,this.setCache(t,r))}deleteCache(t){this.storage.removeItem(t)}clearCache(){this.storage.clear()}}const r=new o(n.Local),s=new o(n.Session);
2
+ //! Function Deep Copy
3
+ const i=t=>e("object",t)||e("function",t);var c;function a(t,e,n){[t[e],t[n]]=[t[n],t[e]]}function u(t,e,n){return n===c.ASC?t>e:t<e}!function(t){t.ASC="ASC",t.DESC="DESC"}(c||(c={}));const l=new Map([["yyyy","year"],["MM","month"],["dd","day"],["HH","hours"],["mm","minutes"],["ss","seconds"],["W","week"]]),f=new Map([[1,"一"],[2,"二"],[3,"三"],[4,"四"],[5,"五"],[6,"六"],[0,"日"]]);function p(t){return t.toString().padStart(2,"0")}exports.bubblingSort=function(t,e=c.ASC,n){const o=t.length;if(o<2)return t;for(let r=0;r<o-1;r++)for(let s=0;s<o-1-r;s++){u(n?t[s][n]:t[s],n?t[s+1][n]:t[s+1],e)&&a(t,s,s+1)}return t},exports.compose=function(...t){const e=t.length;if(!(e<=0)){for(let n=0;n<e;n++){if("function"!=typeof t[n])throw new Error(`argument with index ${n} is not a function`)}return function(...n){let o=0,r=t[o].apply(this,n);for(;++o<e;)r=t[o].call(this,r);return r}}},exports.currying=function(t){return function e(...n){return n.length>=t.length?t.apply(this,n):function(...t){return e.apply(this,n.concat(t))}}},exports.debounce=function(t,e=0,n=!1){let o=null,r=!1;function s(...s){return new Promise(((i,c)=>{if(null!==o&&clearTimeout(o),!n||r)o=setTimeout((()=>{try{const e=t.apply(this,s);i(e)}catch(t){c(t)}finally{o=null,r=!1}}),e);else{try{const e=t.apply(this,s);i(e)}catch(t){c(t)}r=!0}}))}return s.cancel=function(){null!==o&&clearTimeout(o),o=null,r=!1},s},exports.deepClone=function t(n,o=new WeakMap){if(o.get(n))return o.get(n);const r=function(t,n,o){if(e("symbol",t))return Symbol(t.description);if(!i(t))return t;if(e("set",t)){const e=new Set;return t.forEach((t=>e.add(n(t,o)))),e}if(e("map",t)){const e=new Map;return t.forEach(((t,r)=>e.set(r,n(t,o)))),e}}(n,t,o);if(r)return r;const s=e("array",n),c=s?[]:{};return o.set(n,c),s?n.forEach(((e,n)=>{c[n]=t(e,o)})):(Object.keys(n).forEach((e=>{c[e]=t(n[e],o)})),Object.getOwnPropertySymbols(n).forEach((e=>{c[Symbol(e.description)]=t(n[e],o)}))),c},exports.formatTimer=(t,n="yyyy-MM-dd HH:mm:ss")=>{if(!t)return(new Date).toISOString();const o=function(t){const e=0===t.getDay()?7:t.getDay();return{year:t.getFullYear().toString(),month:p(t.getMonth()+1),day:p(t.getDate()),hours:p(t.getHours()),minutes:p(t.getMinutes()),seconds:p(t.getSeconds()),week:(n=e,f.get(n)||""),weekNum:e.toString()};var n}(new Date(t));if(e("string",n)&&!n.trim())return o;return Array.from(l).reduce(((t,[e,n])=>t.replace(new RegExp(e,"g"),o[n])),n)},exports.insertStr=function(t,e,n){return t.slice(0,e)+n+t.slice(e)},exports.isType=e,exports.localCache=r,exports.sessionCache=s,exports.setTimer=function(t,e,n){let o=null;const r=()=>{t(),o=setTimeout(r,e)};return n&&t(),setTimeout(r,e),{cancel:()=>{null!==o&&clearTimeout(o)}}},exports.shallowClone=
4
+ //! Function Shallow Copy
5
+ function(t){return e("array",t)?t.slice():e("object",t)?{...t}:t},exports.stringCase=function(t,e="",n=""){const o=t.split(e);for(let t=0;t<o.length;t++)o[t]=o[t].slice(0,1).toUpperCase()+o[t].slice(1).toLowerCase();return o.join(n)},exports.throttle=function(t,e,n={}){const{leading:o=!0,trailing:r=!1}=n;let s=0,i=null;function c(...n){return new Promise(((c,a)=>{try{const a=Date.now();let u;o||0!==s||(s=a);const l=e-(a-s);if(l<=0)return i&&clearTimeout(i),u=t.apply(this,n),c(u),s=a,void(i=null);r&&!i&&(i=setTimeout((()=>{u=t.apply(this,n),c(u),s=Date.now(),i=null}),l))}catch(t){a(t)}}))}return c.cancel=function(){i&&clearTimeout(i),s=0,i=null},c};
@@ -0,0 +1,67 @@
1
+ declare function currying(fn: Function): (this: any, ...args: any[]) => any;
2
+ declare function compose(...fns: Function[]): ((this: any, ...args: any[]) => any) | undefined;
3
+ declare function insertStr(soure: string, start: number, newStr: string): string;
4
+ declare function stringCase(soure: string, separator?: string, separate?: string): string;
5
+ declare function setTimer(execute: (...args: any[]) => any, delay: number, immediate: boolean): {
6
+ cancel: () => void;
7
+ };
8
+
9
+ declare const isType: (type: string, target: any) => boolean;
10
+
11
+ declare enum CacheType {
12
+ Local = 0,
13
+ Session = 1
14
+ }
15
+ /**
16
+ * Encapsulate storage cache class
17
+ *
18
+ * @class StorageCache
19
+ * @template T
20
+ */
21
+ declare class StorageCache<T = any> {
22
+ private storage;
23
+ constructor(type: CacheType);
24
+ getCache(key: string): T;
25
+ setCache(key: string, value: T): void;
26
+ updateCache(key: string, property: string, value: T): void;
27
+ deleteCache(key: string): void;
28
+ clearCache(): void;
29
+ }
30
+ declare const localCache: StorageCache<any>;
31
+ declare const sessionCache: StorageCache<any>;
32
+
33
+ interface ITimerObj {
34
+ year: string;
35
+ month: string;
36
+ day: string;
37
+ hours: string;
38
+ minutes: string;
39
+ seconds: string;
40
+ week: string;
41
+ weekNum: string;
42
+ }
43
+ type TFormatTimer = (cellValue: string | number | Date, formatType?: string) => string | ITimerObj;
44
+ type ThrottleOptions = {
45
+ leading?: boolean;
46
+ trailing?: boolean;
47
+ };
48
+
49
+ declare function debounce<T extends (...args: any[]) => any>(callback: T, delay?: number, immediate?: boolean): ((...args: Parameters<T>) => Promise<ReturnType<T>>) & {
50
+ cancel: () => void;
51
+ };
52
+ declare function throttle<T extends (...args: any[]) => any>(callback: T, interval: number, options?: ThrottleOptions): ((...args: Parameters<T>) => Promise<ReturnType<T>>) & {
53
+ cancel: () => void;
54
+ };
55
+
56
+ declare function shallowClone<T = any>(source: T): T;
57
+ declare function deepClone(source: any, hash?: WeakMap<object, any>): any;
58
+
59
+ declare enum SortType {
60
+ ASC = "ASC",
61
+ DESC = "DESC"
62
+ }
63
+ declare function bubblingSort<T>(array: T[], type?: SortType, key?: keyof T): T[];
64
+
65
+ declare const formatTimer: TFormatTimer;
66
+
67
+ export { bubblingSort, compose, currying, debounce, deepClone, formatTimer, insertStr, isType, localCache, sessionCache, setTimer, shallowClone, stringCase, throttle };
@@ -0,0 +1,5 @@
1
+ function t(t){return function e(...n){return n.length>=t.length?t.apply(this,n):function(...t){return e.apply(this,n.concat(t))}}}function e(...t){const e=t.length;if(!(e<=0)){for(let n=0;n<e;n++){if("function"!=typeof t[n])throw new Error(`argument with index ${n} is not a function`)}return function(...n){let o=0,r=t[o].apply(this,n);for(;++o<e;)r=t[o].call(this,r);return r}}}function n(t,e,n){return t.slice(0,e)+n+t.slice(e)}function o(t,e="",n=""){const o=t.split(e);for(let t=0;t<o.length;t++)o[t]=o[t].slice(0,1).toUpperCase()+o[t].slice(1).toLowerCase();return o.join(n)}function r(t,e,n){let o=null;const r=()=>{t(),o=setTimeout(r,e)};return n&&t(),setTimeout(r,e),{cancel:()=>{null!==o&&clearTimeout(o)}}}const c={string:t=>"string"==typeof t,number:t=>"number"==typeof t,boolean:t=>"boolean"==typeof t,null:t=>null===t,undefined:t=>void 0===t,symbol:t=>"symbol"==typeof t,bigint:t=>"bigint"==typeof t,object:t=>null!==t&&"object"==typeof t,array:t=>Array.isArray(t),function:t=>"function"==typeof t,set:t=>t instanceof Set,map:t=>t instanceof Map,date:t=>t instanceof Date,regexp:t=>t instanceof RegExp},i=(t,e)=>c[t]?.(e)||!1;var s;!function(t){t[t.Local=0]="Local",t[t.Session=1]="Session"}(s||(s={}));class a{constructor(t){this.storage=t===s.Local?localStorage:sessionStorage}getCache(t){const e=this.storage.getItem(t);return e?JSON.parse(e):null}setCache(t,e){this.storage.setItem(t,JSON.stringify(e))}updateCache(t,e,n){const o=this.getCache(t);i("object",o)&&(o[e]=n,this.setCache(t,o))}deleteCache(t){this.storage.removeItem(t)}clearCache(){this.storage.clear()}}const u=new a(s.Local),l=new a(s.Session);function f(t,e=0,n=!1){let o=null,r=!1;function c(...c){return new Promise(((i,s)=>{if(null!==o&&clearTimeout(o),!n||r)o=setTimeout((()=>{try{const e=t.apply(this,c);i(e)}catch(t){s(t)}finally{o=null,r=!1}}),e);else{try{const e=t.apply(this,c);i(e)}catch(t){s(t)}r=!0}}))}return c.cancel=function(){null!==o&&clearTimeout(o),o=null,r=!1},c}function y(t,e,n={}){const{leading:o=!0,trailing:r=!1}=n;let c=0,i=null;function s(...n){return new Promise(((s,a)=>{try{const a=Date.now();let u;o||0!==c||(c=a);const l=e-(a-c);if(l<=0)return i&&clearTimeout(i),u=t.apply(this,n),s(u),c=a,void(i=null);r&&!i&&(i=setTimeout((()=>{u=t.apply(this,n),s(u),c=Date.now(),i=null}),l))}catch(t){a(t)}}))}return s.cancel=function(){i&&clearTimeout(i),c=0,i=null},s}
2
+ //! Function Shallow Copy
3
+ function g(t){return i("array",t)?t.slice():i("object",t)?{...t}:t}
4
+ //! Function Deep Copy
5
+ const p=t=>i("object",t)||i("function",t);function h(t,e=new WeakMap){if(e.get(t))return e.get(t);const n=function(t,e,n){if(i("symbol",t))return Symbol(t.description);if(!p(t))return t;if(i("set",t)){const o=new Set;return t.forEach((t=>o.add(e(t,n)))),o}if(i("map",t)){const o=new Map;return t.forEach(((t,r)=>o.set(r,e(t,n)))),o}}(t,h,e);if(n)return n;const o=i("array",t),r=o?[]:{};return e.set(t,r),o?t.forEach(((t,n)=>{r[n]=h(t,e)})):(Object.keys(t).forEach((n=>{r[n]=h(t[n],e)})),Object.getOwnPropertySymbols(t).forEach((n=>{r[Symbol(n.description)]=h(t[n],e)}))),r}var m;function S(t,e,n){[t[e],t[n]]=[t[n],t[e]]}function d(t,e,n){return n===m.ASC?t>e:t<e}function w(t,e=m.ASC,n){const o=t.length;if(o<2)return t;for(let r=0;r<o-1;r++)for(let c=0;c<o-1-r;c++){d(n?t[c][n]:t[c],n?t[c+1][n]:t[c+1],e)&&S(t,c,c+1)}return t}!function(t){t.ASC="ASC",t.DESC="DESC"}(m||(m={}));const b=new Map([["yyyy","year"],["MM","month"],["dd","day"],["HH","hours"],["mm","minutes"],["ss","seconds"],["W","week"]]),C=new Map([[1,"一"],[2,"二"],[3,"三"],[4,"四"],[5,"五"],[6,"六"],[0,"日"]]);function M(t){return t.toString().padStart(2,"0")}const D=(t,e="yyyy-MM-dd HH:mm:ss")=>{if(!t)return(new Date).toISOString();const n=function(t){const e=0===t.getDay()?7:t.getDay();return{year:t.getFullYear().toString(),month:M(t.getMonth()+1),day:M(t.getDate()),hours:M(t.getHours()),minutes:M(t.getMinutes()),seconds:M(t.getSeconds()),week:(n=e,C.get(n)||""),weekNum:e.toString()};var n}(new Date(t));if(i("string",e)&&!e.trim())return n;return Array.from(b).reduce(((t,[e,o])=>t.replace(new RegExp(e,"g"),n[o])),e)};export{w as bubblingSort,e as compose,t as currying,f as debounce,h as deepClone,D as formatTimer,n as insertStr,i as isType,u as localCache,l as sessionCache,r as setTimer,g as shallowClone,o as stringCase,y as throttle};
@@ -0,0 +1,5 @@
1
+ !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).Evenex={})}(this,(function(t){"use strict";const e={string:t=>"string"==typeof t,number:t=>"number"==typeof t,boolean:t=>"boolean"==typeof t,null:t=>null===t,undefined:t=>void 0===t,symbol:t=>"symbol"==typeof t,bigint:t=>"bigint"==typeof t,object:t=>null!==t&&"object"==typeof t,array:t=>Array.isArray(t),function:t=>"function"==typeof t,set:t=>t instanceof Set,map:t=>t instanceof Map,date:t=>t instanceof Date,regexp:t=>t instanceof RegExp},n=(t,n)=>e[t]?.(n)||!1;var o;!function(t){t[t.Local=0]="Local",t[t.Session=1]="Session"}(o||(o={}));class r{constructor(t){this.storage=t===o.Local?localStorage:sessionStorage}getCache(t){const e=this.storage.getItem(t);return e?JSON.parse(e):null}setCache(t,e){this.storage.setItem(t,JSON.stringify(e))}updateCache(t,e,o){const r=this.getCache(t);n("object",r)&&(r[e]=o,this.setCache(t,r))}deleteCache(t){this.storage.removeItem(t)}clearCache(){this.storage.clear()}}const i=new r(o.Local),s=new r(o.Session);
2
+ //! Function Deep Copy
3
+ const c=t=>n("object",t)||n("function",t);var a;function u(t,e,n){[t[e],t[n]]=[t[n],t[e]]}function l(t,e,n){return n===a.ASC?t>e:t<e}!function(t){t.ASC="ASC",t.DESC="DESC"}(a||(a={}));const f=new Map([["yyyy","year"],["MM","month"],["dd","day"],["HH","hours"],["mm","minutes"],["ss","seconds"],["W","week"]]),y=new Map([[1,"一"],[2,"二"],[3,"三"],[4,"四"],[5,"五"],[6,"六"],[0,"日"]]);function p(t){return t.toString().padStart(2,"0")}t.bubblingSort=function(t,e=a.ASC,n){const o=t.length;if(o<2)return t;for(let r=0;r<o-1;r++)for(let i=0;i<o-1-r;i++){l(n?t[i][n]:t[i],n?t[i+1][n]:t[i+1],e)&&u(t,i,i+1)}return t},t.compose=function(...t){const e=t.length;if(!(e<=0)){for(let n=0;n<e;n++){if("function"!=typeof t[n])throw new Error(`argument with index ${n} is not a function`)}return function(...n){let o=0,r=t[o].apply(this,n);for(;++o<e;)r=t[o].call(this,r);return r}}},t.currying=function(t){return function e(...n){return n.length>=t.length?t.apply(this,n):function(...t){return e.apply(this,n.concat(t))}}},t.debounce=function(t,e=0,n=!1){let o=null,r=!1;function i(...i){return new Promise(((s,c)=>{if(null!==o&&clearTimeout(o),!n||r)o=setTimeout((()=>{try{const e=t.apply(this,i);s(e)}catch(t){c(t)}finally{o=null,r=!1}}),e);else{try{const e=t.apply(this,i);s(e)}catch(t){c(t)}r=!0}}))}return i.cancel=function(){null!==o&&clearTimeout(o),o=null,r=!1},i},t.deepClone=function t(e,o=new WeakMap){if(o.get(e))return o.get(e);const r=function(t,e,o){if(n("symbol",t))return Symbol(t.description);if(!c(t))return t;if(n("set",t)){const n=new Set;return t.forEach((t=>n.add(e(t,o)))),n}if(n("map",t)){const n=new Map;return t.forEach(((t,r)=>n.set(r,e(t,o)))),n}}(e,t,o);if(r)return r;const i=n("array",e),s=i?[]:{};return o.set(e,s),i?e.forEach(((e,n)=>{s[n]=t(e,o)})):(Object.keys(e).forEach((n=>{s[n]=t(e[n],o)})),Object.getOwnPropertySymbols(e).forEach((n=>{s[Symbol(n.description)]=t(e[n],o)}))),s},t.formatTimer=(t,e="yyyy-MM-dd HH:mm:ss")=>{if(!t)return(new Date).toISOString();const o=function(t){const e=0===t.getDay()?7:t.getDay();return{year:t.getFullYear().toString(),month:p(t.getMonth()+1),day:p(t.getDate()),hours:p(t.getHours()),minutes:p(t.getMinutes()),seconds:p(t.getSeconds()),week:(n=e,y.get(n)||""),weekNum:e.toString()};var n}(new Date(t));if(n("string",e)&&!e.trim())return o;return Array.from(f).reduce(((t,[e,n])=>t.replace(new RegExp(e,"g"),o[n])),e)},t.insertStr=function(t,e,n){return t.slice(0,e)+n+t.slice(e)},t.isType=n,t.localCache=i,t.sessionCache=s,t.setTimer=function(t,e,n){let o=null;const r=()=>{t(),o=setTimeout(r,e)};return n&&t(),setTimeout(r,e),{cancel:()=>{null!==o&&clearTimeout(o)}}},t.shallowClone=
4
+ //! Function Shallow Copy
5
+ function(t){return n("array",t)?t.slice():n("object",t)?{...t}:t},t.stringCase=function(t,e="",n=""){const o=t.split(e);for(let t=0;t<o.length;t++)o[t]=o[t].slice(0,1).toUpperCase()+o[t].slice(1).toLowerCase();return o.join(n)},t.throttle=function(t,e,n={}){const{leading:o=!0,trailing:r=!1}=n;let i=0,s=null;function c(...n){return new Promise(((c,a)=>{try{const a=Date.now();let u;o||0!==i||(i=a);const l=e-(a-i);if(l<=0)return s&&clearTimeout(s),u=t.apply(this,n),c(u),i=a,void(s=null);r&&!s&&(s=setTimeout((()=>{u=t.apply(this,n),c(u),i=Date.now(),s=null}),l))}catch(t){a(t)}}))}return c.cancel=function(){s&&clearTimeout(s),i=0,s=null},c}}));
package/package.json CHANGED
@@ -1,11 +1,16 @@
1
1
  {
2
2
  "name": "devix",
3
3
  "type": "module",
4
- "version": "0.0.12",
4
+ "version": "0.0.14",
5
5
  "description": "Devix is a comprehensive, powerful, and compact JavaScript utility library.",
6
6
  "author": "",
7
7
  "license": "MIT",
8
- "keywords": [],
8
+ "keywords": [
9
+ "devix",
10
+ "utils",
11
+ "tools",
12
+ "develop"
13
+ ],
9
14
  "exports": {
10
15
  ".": {
11
16
  "import": "./dist/index.esm.js",
@@ -15,6 +20,10 @@
15
20
  "main": "./dist/index.cjs.js",
16
21
  "module": "./dist/index.esm.js",
17
22
  "umd": "./dist/index.umd.js",
23
+ "types": "dist/index.d.ts",
24
+ "files": [
25
+ "dist"
26
+ ],
18
27
  "scripts": {
19
28
  "build": "rollup -c",
20
29
  "dev": "yarn build --watch",
package/.babelrc.json DELETED
@@ -1,14 +0,0 @@
1
- {
2
- "presets": [
3
- [
4
- "@babel/preset-env",
5
- {
6
- "modules": false,
7
- "targets": {
8
- "node": "current"
9
- }
10
- }
11
- ],
12
- "@babel/preset-typescript"
13
- ]
14
- }
package/.editorconfig DELETED
@@ -1,14 +0,0 @@
1
- # http://editorconfig.org
2
- root = true
3
-
4
- [*] # 表示所有文件适用
5
- charset = utf-8 # 设置文件字符集为 utf-8
6
- indent_style = space # 缩进风格(tab | space)
7
- indent_size = 2 # 缩进大小
8
- end_of_line = lf # 控制换行类型(lf | cr | crlf)
9
- trim_trailing_whitespace = true # 去除行首的任意空白字符
10
- insert_final_newline = true # 始终在文件末尾插入一个新行
11
-
12
- [*.md] # 表示仅 md 文件适用以下规则
13
- max_line_length = off
14
- trim_trailing_whitespace = false
package/.eslintignore DELETED
@@ -1,2 +0,0 @@
1
- /node_modules
2
- /dist
package/.eslintrc.json DELETED
@@ -1,21 +0,0 @@
1
- {
2
- "env": {
3
- "browser": true,
4
- "es2021": true
5
- },
6
- "extends": [
7
- "eslint:recommended",
8
- "plugin:@typescript-eslint/recommended",
9
- "plugin:prettier/recommended"
10
- ],
11
- "parser": "@typescript-eslint/parser",
12
- "parserOptions": {
13
- "ecmaVersion": "latest",
14
- "sourceType": "module"
15
- },
16
- "plugins": ["@typescript-eslint"],
17
- "rules": {
18
- "@typescript-eslint/no-explicit-any": "off",
19
- "@typescript-eslint/ban-types": "off"
20
- }
21
- }
package/.prettierignore DELETED
@@ -1,9 +0,0 @@
1
- /dist/*
2
- .local
3
- .output.js
4
- /node_modules/**
5
-
6
- **/*.svg
7
- **/*.sh
8
-
9
- /public/*
package/.prettierrc.json DELETED
@@ -1,8 +0,0 @@
1
- {
2
- "useTabs": false,
3
- "tabWidth": 2,
4
- "printWidth": 80,
5
- "singleQuote": true,
6
- "trailingComma": "none",
7
- "semi": false
8
- }
package/jest.config.ts DELETED
@@ -1,25 +0,0 @@
1
- /**
2
- * For a detailed explanation regarding each configuration property, visit:
3
- * https://jestjs.io/docs/configuration
4
- */
5
-
6
- import type { Config } from 'jest'
7
-
8
- const config: Config = {
9
- // Automatically clear mock calls, instances, contexts and results before every test
10
- clearMocks: true,
11
-
12
- // The directory where Jest should output its coverage files
13
- coverageDirectory: 'coverage',
14
-
15
- // Tool selection for test coverage.
16
- coverageProvider: 'babel',
17
-
18
- // Optimization for the extensionsToTreatAsEsm configuration.
19
- extensionsToTreatAsEsm: ['.ts'],
20
-
21
- // Regex matching to ignore collection paths.
22
- coveragePathIgnorePatterns: ['/node_modules/']
23
- }
24
-
25
- export default config
package/rollup.config.js DELETED
@@ -1,59 +0,0 @@
1
- import dts from 'rollup-plugin-dts'
2
- import resolve from '@rollup/plugin-node-resolve'
3
- import commonjs from '@rollup/plugin-commonjs'
4
- import typescript from 'rollup-plugin-typescript2'
5
- import json from '@rollup/plugin-json'
6
- import terser from '@rollup/plugin-terser'
7
- import babel from '@rollup/plugin-babel'
8
- import { DEFAULT_EXTENSIONS } from '@babel/core'
9
-
10
- const packname = 'Evenex'
11
- const entries = ['src/index.ts']
12
- const plugins = [
13
- resolve({
14
- preferBuiltins: true
15
- }),
16
- json(),
17
- commonjs(),
18
- typescript(),
19
- babel({
20
- babelHelpers: 'bundled',
21
- exclude: 'node_modules/**',
22
- extensions: [...DEFAULT_EXTENSIONS, '.ts']
23
- }),
24
- terser()
25
- ]
26
-
27
- const rollup_config = [
28
- ...entries.map((input) => ({
29
- input,
30
- output: [
31
- {
32
- file: input.replace('src/', 'dist/').replace('.ts', '.esm.js'),
33
- format: 'es'
34
- },
35
- {
36
- file: input.replace('src/', 'dist/').replace('.ts', '.cjs.js'),
37
- format: 'cjs'
38
- },
39
- {
40
- name: packname,
41
- file: input.replace('src/', 'dist/').replace('.ts', '.umd.js'),
42
- format: 'umd'
43
- }
44
- ],
45
- plugins
46
- })),
47
- ...entries.map((input) => ({
48
- input,
49
- output: [
50
- {
51
- file: input.replace('src/', 'dist/').replace('.ts', '.d.ts'),
52
- format: 'esm'
53
- }
54
- ],
55
- plugins: [dts({ respectExternal: true })]
56
- }))
57
- ]
58
-
59
- export default rollup_config
package/src/cache.ts DELETED
@@ -1,48 +0,0 @@
1
- import { isType } from './typeof'
2
-
3
- enum CacheType {
4
- Local,
5
- Session
6
- }
7
-
8
- /**
9
- * Encapsulate storage cache class
10
- *
11
- * @class StorageCache
12
- * @template T
13
- */
14
- class StorageCache<T = any> {
15
- private storage: Storage
16
-
17
- constructor(type: CacheType) {
18
- this.storage = type === CacheType.Local ? localStorage : sessionStorage
19
- }
20
-
21
- getCache(key: string): T {
22
- const value: any = this.storage.getItem(key)
23
- return value ? JSON.parse(value) : null
24
- }
25
-
26
- setCache(key: string, value: T): void {
27
- this.storage.setItem(key, JSON.stringify(value))
28
- }
29
-
30
- updateCache(key: string, property: string, value: T) {
31
- const cache: any = this.getCache(key)
32
- if (isType('object', cache)) {
33
- cache[property] = value
34
- this.setCache(key, cache)
35
- }
36
- }
37
-
38
- deleteCache(key: string): void {
39
- this.storage.removeItem(key)
40
- }
41
-
42
- clearCache(): void {
43
- this.storage.clear()
44
- }
45
- }
46
-
47
- export const localCache = new StorageCache(CacheType.Local)
48
- export const sessionCache = new StorageCache(CacheType.Session)
package/src/clone.ts DELETED
@@ -1,64 +0,0 @@
1
- import { isType } from './typeof'
2
-
3
- //! Function Shallow Copy
4
- export function shallowClone<T = any>(source: T): T {
5
- if (isType('array', source)) return (source as any[]).slice() as T
6
- if (isType('object', source)) return { ...source } as T
7
-
8
- return source
9
- }
10
-
11
- //! Function Deep Copy
12
- const isFormat = (target: any) =>
13
- isType('object', target) || isType('function', target)
14
-
15
- function handleSpeciBoundar<T = any>(
16
- source: any,
17
- deepClone: Function,
18
- hash: WeakMap<object, T>
19
- ) {
20
- if (isType('symbol', source)) return Symbol(source.description)
21
-
22
- if (!isFormat(source)) return source
23
-
24
- if (isType('set', source)) {
25
- const newSet = new Set()
26
- source.forEach((value: T) => newSet.add(deepClone(value, hash)))
27
-
28
- return newSet
29
- }
30
- if (isType('map', source)) {
31
- const newMap = new Map()
32
- source.forEach((value: T, key: T) =>
33
- newMap.set(key, deepClone(value, hash))
34
- )
35
- return newMap
36
- }
37
- }
38
-
39
- export function deepClone(source: any, hash = new WeakMap<object, any>()) {
40
- if (hash.get(source)) return hash.get(source)
41
-
42
- const result = handleSpeciBoundar(source, deepClone, hash)
43
- if (result) return result
44
-
45
- const isArray = isType('array', source)
46
- const cloneObject: any = isArray ? [] : {}
47
-
48
- hash.set(source, cloneObject)
49
-
50
- if (isArray) {
51
- ;(source as Array<any>).forEach((item, index) => {
52
- cloneObject[index] = deepClone(item, hash)
53
- })
54
- } else {
55
- Object.keys(source).forEach((key) => {
56
- cloneObject[key] = deepClone(source[key], hash)
57
- })
58
- Object.getOwnPropertySymbols(source).forEach((sym) => {
59
- cloneObject[Symbol(sym.description)] = deepClone(source[sym], hash)
60
- })
61
- }
62
-
63
- return cloneObject
64
- }
package/src/format.ts DELETED
@@ -1,65 +0,0 @@
1
- import { isType } from './typeof'
2
- import { TFormatTimer, ITimerObj } from './types'
3
-
4
- const formatRules = new Map<string, keyof ITimerObj>([
5
- ['yyyy', 'year'],
6
- ['MM', 'month'],
7
- ['dd', 'day'],
8
- ['HH', 'hours'],
9
- ['mm', 'minutes'],
10
- ['ss', 'seconds'],
11
- ['W', 'week']
12
- ])
13
-
14
- const WeekList = new Map<number, string>([
15
- [1, '一'],
16
- [2, '二'],
17
- [3, '三'],
18
- [4, '四'],
19
- [5, '五'],
20
- [6, '六'],
21
- [0, '日']
22
- ])
23
-
24
- function processWeek(weekNum: number): string {
25
- return WeekList.get(weekNum) || ''
26
- }
27
-
28
- function formatNumber(value: number): string {
29
- return value.toString().padStart(2, '0')
30
- }
31
-
32
- function createTimerObj(date: Date): ITimerObj {
33
- const dayOfWeek = date.getDay() === 0 ? 7 : date.getDay()
34
- return {
35
- year: date.getFullYear().toString(),
36
- month: formatNumber(date.getMonth() + 1),
37
- day: formatNumber(date.getDate()),
38
- hours: formatNumber(date.getHours()),
39
- minutes: formatNumber(date.getMinutes()),
40
- seconds: formatNumber(date.getSeconds()),
41
- week: processWeek(dayOfWeek),
42
- weekNum: dayOfWeek.toString()
43
- }
44
- }
45
-
46
- export const formatTimer: TFormatTimer = (
47
- cellValue,
48
- formatType = 'yyyy-MM-dd HH:mm:ss'
49
- ) => {
50
- if (!cellValue) return new Date().toISOString()
51
-
52
- const date = new Date(cellValue)
53
- const timerObj = createTimerObj(date)
54
-
55
- if (isType('string', formatType) && !formatType.trim()) return timerObj
56
-
57
- const timerStr = Array.from(formatRules).reduce(
58
- (currentFormat, [rule, key]) => {
59
- return currentFormat.replace(new RegExp(rule, 'g'), timerObj[key])
60
- },
61
- formatType
62
- )
63
-
64
- return timerStr
65
- }
package/src/index.ts DELETED
@@ -1,7 +0,0 @@
1
- export * from './others'
2
- export * from './typeof'
3
- export * from './cache'
4
- export * from './retalimit'
5
- export * from './clone'
6
- export * from './sort'
7
- export * from './format'
package/src/others.ts DELETED
@@ -1,68 +0,0 @@
1
- export function currying(fn: Function) {
2
- function curried(this: any, ...args: any[]) {
3
- if (args.length >= fn.length) {
4
- return fn.apply(this, args)
5
- } else {
6
- return function (this: any, ...args2: any[]) {
7
- return curried.apply(this, args.concat(args2))
8
- }
9
- }
10
- }
11
- return curried
12
- }
13
-
14
- export function compose(...fns: Function[]) {
15
- const length = fns.length
16
- if (length <= 0) return
17
- for (let i = 0; i < length; i++) {
18
- const fn = fns[i]
19
- if (typeof fn !== 'function') {
20
- throw new Error(`argument with index ${i} is not a function`)
21
- }
22
- }
23
-
24
- return function (this: any, ...args: any[]) {
25
- let index = 0
26
- let result = fns[index].apply(this, args)
27
- while (++index < length) {
28
- result = fns[index].call(this, result)
29
- }
30
- return result
31
- }
32
- }
33
-
34
- export function insertStr(soure: string, start: number, newStr: string) {
35
- return soure.slice(0, start) + newStr + soure.slice(start)
36
- }
37
-
38
- export function stringCase(soure: string, separator = '', separate = '') {
39
- const newStr = soure.split(separator)
40
- for (let i = 0; i < newStr.length; i++) {
41
- newStr[i] =
42
- newStr[i].slice(0, 1).toUpperCase() + newStr[i].slice(1).toLowerCase()
43
- }
44
- return newStr.join(separate)
45
- }
46
-
47
- export function setTimer(
48
- execute: (...args: any[]) => any,
49
- delay: number,
50
- immediate: boolean
51
- ) {
52
- let timer: ReturnType<typeof setTimeout> | null = null
53
-
54
- const interval = () => {
55
- execute()
56
- timer = setTimeout(interval, delay)
57
- }
58
-
59
- if (immediate) execute()
60
-
61
- setTimeout(interval, delay)
62
-
63
- return {
64
- cancel: () => {
65
- if (timer !== null) clearTimeout(timer)
66
- }
67
- }
68
- }
package/src/retalimit.ts DELETED
@@ -1,100 +0,0 @@
1
- import { ThrottleOptions } from './types'
2
-
3
- export function debounce<T extends (...args: any[]) => any>(
4
- callback: T,
5
- delay: number = 0,
6
- immediate: boolean = false
7
- ): ((...args: Parameters<T>) => Promise<ReturnType<T>>) & {
8
- cancel: () => void
9
- } {
10
- let timer: ReturnType<typeof setTimeout> | null = null
11
- let isInvoke: boolean = false
12
-
13
- function _debounce(this: any, ...args: Parameters<T>) {
14
- return new Promise<ReturnType<T>>((resolve, reject) => {
15
- if (timer !== null) clearTimeout(timer)
16
-
17
- if (immediate && !isInvoke) {
18
- try {
19
- const result: ReturnType<T> = callback.apply(this, args)
20
- resolve(result)
21
- } catch (error) {
22
- reject(error)
23
- }
24
- isInvoke = true
25
- return
26
- }
27
-
28
- timer = setTimeout(() => {
29
- try {
30
- const result: ReturnType<T> = callback.apply(this, args)
31
- resolve(result)
32
- } catch (error) {
33
- reject(error)
34
- } finally {
35
- timer = null
36
- isInvoke = false
37
- }
38
- }, delay)
39
- })
40
- }
41
-
42
- _debounce.cancel = function (): void {
43
- if (timer !== null) clearTimeout(timer)
44
- timer = null
45
- isInvoke = false
46
- }
47
-
48
- return _debounce
49
- }
50
-
51
- export function throttle<T extends (...args: any[]) => any>(
52
- callback: T,
53
- interval: number,
54
- options: ThrottleOptions = {}
55
- ): ((...args: Parameters<T>) => Promise<ReturnType<T>>) & {
56
- cancel: () => void
57
- } {
58
- const { leading = true, trailing = false } = options
59
- let startTime: number = 0
60
- let timer: ReturnType<typeof setTimeout> | null = null
61
-
62
- function _throttle(this: any, ...args: Parameters<T>) {
63
- return new Promise<ReturnType<T>>((resolve, reject) => {
64
- try {
65
- const nowTime = Date.now()
66
- let result: ReturnType<T>
67
- if (!leading && startTime === 0) startTime = nowTime
68
-
69
- const waitTime = interval - (nowTime - startTime)
70
- if (waitTime <= 0) {
71
- if (timer) clearTimeout(timer)
72
- result = callback.apply(this, args)
73
- resolve(result)
74
- startTime = nowTime
75
- timer = null
76
- return
77
- }
78
-
79
- if (trailing && !timer) {
80
- timer = setTimeout(() => {
81
- result = callback.apply(this, args)
82
- resolve(result)
83
- startTime = Date.now()
84
- timer = null
85
- }, waitTime)
86
- }
87
- } catch (error) {
88
- reject(error)
89
- }
90
- })
91
- }
92
-
93
- _throttle.cancel = function () {
94
- if (timer) clearTimeout(timer)
95
- startTime = 0
96
- timer = null
97
- }
98
-
99
- return _throttle
100
- }
package/src/sort.ts DELETED
@@ -1,32 +0,0 @@
1
- enum SortType {
2
- ASC = 'ASC',
3
- DESC = 'DESC'
4
- }
5
-
6
- function swap<T>(array: T[], index1: number, index2: number): void {
7
- ;[array[index1], array[index2]] = [array[index2], array[index1]]
8
- }
9
-
10
- function compare<T>(value1: T, value2: T, type: SortType): boolean {
11
- return type === SortType.ASC ? value1 > value2 : value1 < value2
12
- }
13
-
14
- export function bubblingSort<T>(
15
- array: T[],
16
- type: SortType = SortType.ASC,
17
- key?: keyof T
18
- ): T[] {
19
- const length = array.length
20
- if (length < 2) return array
21
-
22
- for (let i = 0; i < length - 1; i++) {
23
- for (let j = 0; j < length - 1 - i; j++) {
24
- const value1 = key ? array[j][key] : array[j]
25
- const value2 = key ? array[j + 1][key] : array[j + 1]
26
-
27
- if (compare(value1, value2, type)) swap(array, j, j + 1)
28
- }
29
- }
30
-
31
- return array
32
- }
package/src/typeof.ts DELETED
@@ -1,26 +0,0 @@
1
- export default function getDataType(target: any) {
2
- const type = typeof target
3
- return type === 'object'
4
- ? type
5
- : Object.prototype.toString.call(target).slice(8, -1).toLowerCase()
6
- }
7
-
8
- const typeCheckers: { [key: string]: (target: any) => boolean } = {
9
- string: (target) => typeof target === 'string',
10
- number: (target) => typeof target === 'number',
11
- boolean: (target) => typeof target === 'boolean',
12
- null: (target) => target === null,
13
- undefined: (target) => typeof target === 'undefined',
14
- symbol: (target) => typeof target === 'symbol',
15
- bigint: (target) => typeof target === 'bigint',
16
- object: (target) => target !== null && typeof target === 'object',
17
- array: (target) => Array.isArray(target),
18
- function: (target) => typeof target === 'function',
19
- set: (target) => target instanceof Set,
20
- map: (target) => target instanceof Map,
21
- date: (target) => target instanceof Date,
22
- regexp: (target) => target instanceof RegExp
23
- }
24
-
25
- export const isType = (type: string, target: any) =>
26
- typeCheckers[type]?.(target) || false
package/src/types.ts DELETED
@@ -1,22 +0,0 @@
1
- //! format types
2
- export interface ITimerObj {
3
- year: string
4
- month: string
5
- day: string
6
- hours: string
7
- minutes: string
8
- seconds: string
9
- week: string
10
- weekNum: string
11
- }
12
-
13
- export type TFormatTimer = (
14
- cellValue: string | number | Date,
15
- formatType?: string
16
- ) => string | ITimerObj
17
-
18
- //! retalimit types
19
- export type ThrottleOptions = {
20
- leading?: boolean
21
- trailing?: boolean
22
- }
File without changes
package/test/test.js DELETED
@@ -1,117 +0,0 @@
1
- import { debounce } from '../dist/index.esm.js'
2
-
3
- // function debounce(callback, delay = 0, immediate = false) {
4
- // let timer = null
5
- // let isInvoke = false
6
- // function _debounce(...args) {
7
- // return new Promise((resolve, reject) => {
8
- // try {
9
- // if (timer) clearTimeout(timer)
10
-
11
- // let result = undefined
12
- // if (immediate && !isInvoke) {
13
- // result = callback.apply(this, args)
14
- // resolve(result)
15
- // isInvoke = true
16
- // return
17
- // }
18
-
19
- // timer = setTimeout(() => {
20
- // result = callback.apply(this, args)
21
- // resolve(result)
22
- // timer = null
23
- // isInvoke = false
24
- // }, delay)
25
- // } catch (error) {
26
- // reject(error)
27
- // }
28
- // })
29
- // }
30
-
31
- // _debounce.cancel = function () {
32
- // if (timer) clearTimeout(timer)
33
- // timer = null
34
- // isInvoke = false
35
- // }
36
-
37
- // return _debounce
38
- // }
39
-
40
- // function throttle(
41
- // callback,
42
- // interval,
43
- // { leading = true, trailing = false } = {}
44
- // ) {
45
- // let startTime = 0
46
- // let timer = null
47
- // function _throttle(...args) {
48
- // return new Promise((resolve, reject) => {
49
- // try {
50
- // const nowTime = Date.now()
51
- // let result = undefined
52
- // if (!leading && startTime === 0) startTime = nowTime
53
-
54
- // const waitTime = interval - (nowTime - startTime)
55
- // if (waitTime <= 0) {
56
- // if (timer) clearTimeout(timer)
57
- // result = callback.apply(this, args)
58
- // resolve(result)
59
- // startTime = nowTime
60
- // timer = null
61
- // return
62
- // }
63
-
64
- // if (trailing && !timer) {
65
- // timer = setTimeout(() => {
66
- // result = callback.apply(this, args)
67
- // resolve(result)
68
- // startTime = Date.now()
69
- // timer = null
70
- // }, waitTime)
71
- // }
72
- // } catch (error) {
73
- // reject(error)
74
- // }
75
- // })
76
- // }
77
-
78
- // _throttle.cancel = function () {
79
- // if (timer) clearTimeout(timer)
80
- // startTime = 0
81
- // timer = null
82
- // }
83
-
84
- // return _throttle
85
- // }
86
-
87
- // const foo1 = debounce(
88
- // (message) => {
89
- // console.log('message', message)
90
- // return message
91
- // },
92
- // 3000,
93
- // true
94
- // )
95
-
96
- // const foop1 = foo1('111')
97
- // foop1.then((res) => {
98
- // console.log(`res:`, res)
99
- // })
100
- // // foo1('222')
101
- // foo1('333')
102
-
103
- // setTimeout(() => {
104
- // foo1.cancel()
105
- // }, 1000)
106
-
107
- const foo3 = debounce(function (...args) {
108
- console.log('this', this)
109
- console.log('args', args)
110
- })
111
-
112
- const obj1 = {
113
- name: 'obj',
114
- foo3
115
- }
116
-
117
- obj1.foo3('333')
package/tsconfig.json DELETED
@@ -1,16 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "esnext",
4
- "module": "esnext",
5
- "lib": ["esnext", "DOM", "DOM.Iterable"],
6
- "useDefineForClassFields": true,
7
- "skipLibCheck": true,
8
- "moduleResolution": "node",
9
- "resolveJsonModule": true,
10
- "esModuleInterop": false,
11
- "strict": true,
12
- "strictNullChecks": true,
13
- "typeRoots": ["node_modules/@types", "src/types.ts"]
14
- },
15
- "include": ["src/*.ts"]
16
- }