devix 0.0.22 → 0.0.23-beta.10

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
@@ -1,36 +1,36 @@
1
1
  # devix
2
2
 
3
- > devix 是一个全面的、强大的、紧凑的 JavaScript 实用程序库( 简体中文 | [English](README_en.md) )
3
+ > Devix is a comprehensive, powerful, and compact JavaScript utility library.( English | [简体中文](README.md) )
4
4
 
5
- ## 安装
5
+ ## Install
6
6
 
7
- 请确保您在 Node.js 环境下使用 npm 或其他包管理器安装此库。
7
+ Please make sure you install this library using npm or another package manager in a Node.js environment.
8
8
 
9
9
  ```shell
10
10
  npm install --save-dev devix
11
11
  ```
12
12
 
13
- 然后,利用现代的模块捆绑工具,如 Vite Webpack,以模块化的语法引入此库。
13
+ Then, utilize modern module bundling tools such as Vite or Webpack to import this library using modular syntax.
14
14
 
15
15
  ```javascript
16
- // 使用 ES Module
16
+ // Using ES Module
17
17
  import { [[ModuleName]] } from 'devix'
18
18
 
19
- // 使用 CommonJS
19
+ // Using CommonJS
20
20
  const { [[ModuleName]] } = require('devix')
21
21
  ```
22
22
 
23
- ## 使用
23
+ ## Usage
24
24
 
25
25
  ```javascript
26
26
  import { localCache, bubblingSort, isType } from 'devix'
27
27
 
28
- // 使用 localCache
28
+ // Using localCache
29
29
  localCache.setCache('userInfo', { name: 'king', age: 18 })
30
30
  const userInfo = localCache.get('userInfo')
31
31
  console.log('userInfo', userInfo)
32
32
 
33
- // 使用 bubblingSort、
33
+ // Using bubblingSort、
34
34
  const arr1 = [123, 346, 62, 2456, 56123, 1, 64, 61, 453, 72345]
35
35
  const sortArr1 = bubblingSort(arr1, 'DESC')
36
36
  console.log('sortArr1', sortArr1)
@@ -43,7 +43,7 @@ const arr2 = [
43
43
  const sortArr2 = bubblingSort(arr2, 'DESC', 'age')
44
44
  console.log('sortArr2', sortArr2)
45
45
 
46
- // 使用 isType
46
+ // Using isType
47
47
  console.log(`isType(userInfo,'object') -> true`, isType(userInfo, 'object'))
48
48
  console.log(
49
49
  `isType(userInfo.name,'string') -> true`,
@@ -52,51 +52,51 @@ console.log(
52
52
  console.log(`isType(userInfo.age,'number') -> true`, isType(userInfo, 'number'))
53
53
  ```
54
54
 
55
- ## 方法
55
+ ## API
56
56
 
57
- ### 缓存相关
57
+ ### Cache Apis
58
58
 
59
- 提供缓存操作的相关方法。
59
+ Provides methods related to cache operations.
60
60
 
61
61
  - localCache
62
62
  - sessionCache
63
63
 
64
- ### 拷贝相关
64
+ ### Clone Apis
65
65
 
66
- 用于数据复制操作的相关方法。
66
+ Methods for data cloning operations.
67
67
 
68
68
  - deepClone
69
69
  - shallowClone
70
70
 
71
- ### 限频相关
71
+ ### Retalimit Apis
72
72
 
73
- 包含控制操作触发频率的相关方法。
73
+ Includes methods for controlling the frequency of operations.
74
74
 
75
75
  - throttle
76
76
  - debounce
77
77
 
78
- ### 排序相关
78
+ ### Sort Apis
79
79
 
80
- 提供各种排序操作的方法。
80
+ Offers methods for various sorting operations.
81
81
 
82
82
  - bubblingSort
83
83
 
84
- ### 时间相关
84
+ ### Time Apis
85
85
 
86
- 包括处理时间相关操作的方法。
86
+ Consists of methods for handling time-related operations.
87
87
 
88
88
  - formatTimer
89
89
  - setTimer
90
90
 
91
- ### 类型相关
91
+ ### Typeof Apis
92
92
 
93
- 用于数据类型检测的相关方法。
93
+ Methods for data type detection.
94
94
 
95
95
  - isType
96
96
 
97
- ### 其他方法
97
+ ### Other Apis
98
98
 
99
- 包括各种其他功能性函数和方法。
99
+ Includes a variety of other functional functions and methods.
100
100
 
101
101
  - compose
102
102
  - currying
package/dist/index.js ADDED
@@ -0,0 +1,306 @@
1
+ 'use strict';
2
+
3
+ function getDataType(target) {
4
+ const type = typeof target;
5
+ return type != "object" ? type : Object.prototype.toString.call(target).slice(8, -1).toLowerCase();
6
+ }
7
+ const typeCheckers = {
8
+ // DataType
9
+ undefined: (target) => typeof target === "undefined",
10
+ null: (target) => target === null,
11
+ number: (target) => typeof target === "number",
12
+ string: (target) => typeof target === "string",
13
+ boolean: (target) => typeof target === "boolean",
14
+ symbol: (target) => typeof target === "symbol",
15
+ bigint: (target) => typeof target === "bigint",
16
+ // ObjectType
17
+ object: (target) => target !== null && typeof target === "object",
18
+ array: (target) => Array.isArray(target),
19
+ date: (target) => target instanceof Date,
20
+ function: (target) => typeof target === "function",
21
+ set: (target) => target instanceof Set,
22
+ map: (target) => target instanceof Map,
23
+ regexp: (target) => target instanceof RegExp,
24
+ promise: (target) => target instanceof Promise,
25
+ // ExpandType
26
+ empty: (target) => !(target !== null && target !== "" && typeof target !== "undefined")
27
+ };
28
+ const isType = (type, target) => {
29
+ const dataType = typeCheckers[type] ? typeCheckers[type](target) : getDataType(target) === type;
30
+ return dataType;
31
+ };
32
+
33
+ function currying(fn) {
34
+ function curried(...args) {
35
+ if (args.length >= fn.length) {
36
+ return fn.apply(this, args);
37
+ } else {
38
+ return function(...args2) {
39
+ return curried.apply(this, args.concat(args2));
40
+ };
41
+ }
42
+ }
43
+ return curried;
44
+ }
45
+ function compose(...fns) {
46
+ const length = fns.length;
47
+ if (length <= 0) return;
48
+ for (let i = 0; i < length; i++) {
49
+ const fn = fns[i];
50
+ if (typeof fn !== "function") {
51
+ throw new Error(`argument with index ${i} is not a function`);
52
+ }
53
+ }
54
+ return function(...args) {
55
+ let index = 0;
56
+ let result = fns[index].apply(this, args);
57
+ while (++index < length) {
58
+ result = fns[index].call(this, result);
59
+ }
60
+ return result;
61
+ };
62
+ }
63
+ function insertStr(soure, start, newStr) {
64
+ return soure.slice(0, start) + newStr + soure.slice(start);
65
+ }
66
+ function stringCase(soure, separa = ["", ""], cases = ["upper", "upper"]) {
67
+ const [separator, separate] = separa;
68
+ const [firstCase, argsCase] = cases;
69
+ const newStr = soure.split(separator);
70
+ for (let i = 0; i < newStr.length; i++) {
71
+ newStr[i] = setCaseType(newStr[i], i === 0 ? firstCase : argsCase);
72
+ }
73
+ return newStr.join(separate);
74
+ }
75
+ function setCaseType(soure, caseType) {
76
+ const newStr = soure.slice(0, 1)[caseType === "upper" ? "toUpperCase" : "toLowerCase"]() + soure.slice(1).toLowerCase();
77
+ return newStr;
78
+ }
79
+ const transformGetParams = (params) => {
80
+ let result = "";
81
+ for (const propName of Object.keys(params)) {
82
+ const value = params[propName];
83
+ const part = `${encodeURIComponent(propName)}=`;
84
+ if (isType("empty", value)) continue;
85
+ if (!isType("object", value)) {
86
+ result += `${part + encodeURIComponent(value)}&`;
87
+ continue;
88
+ }
89
+ for (const key of Object.keys(value)) {
90
+ if (isType("empty", value)) continue;
91
+ const params2 = propName + `[${key}]`;
92
+ const subPart = `${encodeURIComponent(params2)}=`;
93
+ result += `${subPart + encodeURIComponent(value[key])}&`;
94
+ }
95
+ }
96
+ return result.slice(0, -1);
97
+ };
98
+
99
+ function debounce(callback, delay = 0, immediate = false) {
100
+ let timer = null;
101
+ let isInvoke = false;
102
+ function _debounce(...args) {
103
+ return new Promise((resolve, reject) => {
104
+ if (timer !== null) clearTimeout(timer);
105
+ if (immediate && !isInvoke) {
106
+ try {
107
+ const result = callback.apply(this, args);
108
+ resolve(result);
109
+ } catch (error) {
110
+ reject(error);
111
+ }
112
+ isInvoke = true;
113
+ return;
114
+ }
115
+ timer = setTimeout(() => {
116
+ try {
117
+ const result = callback.apply(this, args);
118
+ resolve(result);
119
+ } catch (error) {
120
+ reject(error);
121
+ } finally {
122
+ timer = null;
123
+ isInvoke = false;
124
+ }
125
+ }, delay);
126
+ });
127
+ }
128
+ _debounce.cancel = function() {
129
+ if (timer !== null) clearTimeout(timer);
130
+ timer = null;
131
+ isInvoke = false;
132
+ };
133
+ return _debounce;
134
+ }
135
+ function throttle(callback, interval, options = {}) {
136
+ const {
137
+ leading = true,
138
+ trailing = false
139
+ } = options;
140
+ let startTime = 0;
141
+ let timer = null;
142
+ function _throttle(...args) {
143
+ return new Promise((resolve, reject) => {
144
+ try {
145
+ const nowTime = Date.now();
146
+ let result;
147
+ if (!leading && startTime === 0) startTime = nowTime;
148
+ const waitTime = interval - (nowTime - startTime);
149
+ if (waitTime <= 0) {
150
+ if (timer) clearTimeout(timer);
151
+ result = callback.apply(this, args);
152
+ resolve(result);
153
+ startTime = nowTime;
154
+ timer = null;
155
+ return;
156
+ }
157
+ if (trailing && !timer) {
158
+ timer = setTimeout(() => {
159
+ result = callback.apply(this, args);
160
+ resolve(result);
161
+ startTime = Date.now();
162
+ timer = null;
163
+ }, waitTime);
164
+ }
165
+ } catch (error) {
166
+ reject(error);
167
+ }
168
+ });
169
+ }
170
+ _throttle.cancel = function() {
171
+ if (timer) clearTimeout(timer);
172
+ startTime = 0;
173
+ timer = null;
174
+ };
175
+ return _throttle;
176
+ }
177
+
178
+ //! Function Shallow Copy
179
+ function shallowClone(source) {
180
+ if (isType("array", source)) return source.slice();
181
+ if (isType("object", source)) return {
182
+ ...source
183
+ };
184
+ return source;
185
+ }
186
+ //! Function Deep Copy
187
+ const isFormat = (target) => isType("object", target) || isType("function", target);
188
+ function handleSpeciBoundar(source, deepClone2, hash) {
189
+ if (isType("symbol", source)) return Symbol(source.description);
190
+ if (!isFormat(source)) return source;
191
+ if (isType("set", source)) {
192
+ const newSet = /* @__PURE__ */ new Set();
193
+ source.forEach((value) => newSet.add(deepClone2(value, hash)));
194
+ return newSet;
195
+ }
196
+ if (isType("map", source)) {
197
+ const newMap = /* @__PURE__ */ new Map();
198
+ source.forEach((value, key) => newMap.set(key, deepClone2(value, hash)));
199
+ return newMap;
200
+ }
201
+ }
202
+ function deepClone(source, hash = /* @__PURE__ */ new WeakMap()) {
203
+ if (hash.get(source)) return hash.get(source);
204
+ const result = handleSpeciBoundar(source, deepClone, hash);
205
+ if (result) return result;
206
+ const isArray = isType("array", source);
207
+ const cloneObject = isArray ? [] : {};
208
+ hash.set(source, cloneObject);
209
+ if (isArray) {
210
+ source.forEach((item, index) => {
211
+ cloneObject[index] = deepClone(item, hash);
212
+ });
213
+ } else {
214
+ Object.keys(source).forEach((key) => {
215
+ cloneObject[key] = deepClone(source[key], hash);
216
+ });
217
+ Object.getOwnPropertySymbols(source).forEach((sym) => {
218
+ cloneObject[Symbol(sym.description)] = deepClone(source[sym], hash);
219
+ });
220
+ }
221
+ return cloneObject;
222
+ }
223
+
224
+ exports.SortType = void 0;
225
+ (function(SortType2) {
226
+ SortType2["ASC"] = "ASC";
227
+ SortType2["DESC"] = "DESC";
228
+ })(exports.SortType || (exports.SortType = {}));
229
+ function swap(array, index1, index2) {
230
+ [array[index1], array[index2]] = [array[index2], array[index1]];
231
+ }
232
+ function compare(value1, value2, type) {
233
+ return type === exports.SortType.ASC ? value1 > value2 : value1 < value2;
234
+ }
235
+ function bubblingSort(array, type = "ASC", key) {
236
+ const length = array.length;
237
+ if (length < 2) return array;
238
+ for (let i = 0; i < length - 1; i++) {
239
+ for (let j = 0; j < length - 1 - i; j++) {
240
+ const value1 = key ? array[j][key] : array[j];
241
+ const value2 = key ? array[j + 1][key] : array[j + 1];
242
+ if (compare(value1, value2, type)) swap(array, j, j + 1);
243
+ }
244
+ }
245
+ return array;
246
+ }
247
+
248
+ const formatRules = /* @__PURE__ */ new Map([["yyyy", "year"], ["MM", "month"], ["dd", "day"], ["HH", "hours"], ["mm", "minutes"], ["ss", "seconds"], ["W", "week"]]);
249
+ const WeekList = /* @__PURE__ */ new Map([[1, "\u4E00"], [2, "\u4E8C"], [3, "\u4E09"], [4, "\u56DB"], [5, "\u4E94"], [6, "\u516D"], [0, "\u65E5"]]);
250
+ function processWeek(weekNum) {
251
+ return WeekList.get(weekNum) || "";
252
+ }
253
+ function formatNumber(value) {
254
+ return value.toString().padStart(2, "0");
255
+ }
256
+ function createTimerObj(date) {
257
+ const dayOfWeek = date.getDay() === 0 ? 7 : date.getDay();
258
+ return {
259
+ year: date.getFullYear().toString(),
260
+ month: formatNumber(date.getMonth() + 1),
261
+ day: formatNumber(date.getDate()),
262
+ hours: formatNumber(date.getHours()),
263
+ minutes: formatNumber(date.getMinutes()),
264
+ seconds: formatNumber(date.getSeconds()),
265
+ week: processWeek(dayOfWeek),
266
+ weekNum: dayOfWeek.toString()
267
+ };
268
+ }
269
+ const formatTimer = (cellValue, formatType = "yyyy-MM-dd HH:mm:ss") => {
270
+ if (!cellValue) return (/* @__PURE__ */ new Date()).toISOString();
271
+ const date = new Date(cellValue);
272
+ const timerObj = createTimerObj(date);
273
+ if (isType("string", formatType) && !formatType.trim()) return timerObj;
274
+ const timerStr = Array.from(formatRules).reduce((currentFormat, [rule, key]) => {
275
+ return currentFormat.replace(new RegExp(rule, "g"), timerObj[key]);
276
+ }, formatType);
277
+ return timerStr;
278
+ };
279
+ async function setTimer(execute, delay = 0, immediate = false) {
280
+ let timer = null;
281
+ const interval = async () => {
282
+ await execute();
283
+ timer = setTimeout(interval, delay);
284
+ };
285
+ if (immediate) await execute();
286
+ setTimeout(interval, delay);
287
+ return {
288
+ cancel: () => {
289
+ if (timer !== null) clearTimeout(timer);
290
+ }
291
+ };
292
+ }
293
+
294
+ exports.bubblingSort = bubblingSort;
295
+ exports.compose = compose;
296
+ exports.currying = currying;
297
+ exports.debounce = debounce;
298
+ exports.deepClone = deepClone;
299
+ exports.formatTimer = formatTimer;
300
+ exports.insertStr = insertStr;
301
+ exports.isType = isType;
302
+ exports.setTimer = setTimer;
303
+ exports.shallowClone = shallowClone;
304
+ exports.stringCase = stringCase;
305
+ exports.throttle = throttle;
306
+ exports.transformGetParams = transformGetParams;