@gateweb/react-utils 1.7.1 → 1.9.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.
package/dist/es/index.mjs CHANGED
@@ -1,306 +1,153 @@
1
1
  import dayjs from 'dayjs';
2
+ export { Q as QueryProvider, u as useQueryContext } from './queryStore-client-vG-bXFYm.mjs';
2
3
  export { u as useCountdown } from './useCountdown-client-t52WIHfq.mjs';
3
4
  import { useState, useCallback } from 'react';
4
- export { Q as QueryProvider, u as useQueryContext } from './queryStore-client-CFQTVwrg.mjs';
5
5
  export { d as downloadFile } from './download-client-CnaJ0p_f.mjs';
6
6
  export { g as getLocalStorage, s as setLocalStorage } from './webStorage-client-Pd-loNCg.mjs';
7
7
 
8
+ const FILE_SIZE_UNITS$1 = [
9
+ 'Bytes',
10
+ 'KB',
11
+ 'MB',
12
+ 'GB',
13
+ 'TB',
14
+ 'PB',
15
+ 'EB',
16
+ 'ZB',
17
+ 'YB'
18
+ ];
8
19
  /**
9
- * convert CamelCase string to PascalCase string
10
- * @param str the string to convert
11
- * @example
12
- * camelString2PascalString('camelCase') // 'CamelCase'
13
- * camelString2PascalString('camelCaseTest') // 'CamelCaseTest'
14
- */ const camelString2PascalString = (str)=>`${str[0].toUpperCase()}${str.slice(1)}`;
15
- /**
16
- * convert CamelCase string to SnakeCase string
17
- * @param str the string to convert
18
- * @example
19
- * camelString2SnakeString('camelCase') // 'camel_case'
20
- * camelString2SnakeString('camelCaseTest') // 'camel_case_test'
21
- */ const camelString2SnakeString = (str)=>str.replace(/[A-Z]/g, (letter)=>`_${letter.toLowerCase()}`);
22
- /**
23
- * convert PascalCase string to CamelCase string
24
- * @param str the string to convert
25
- * @example
26
- * pascalString2CamelString('PascalCase') // 'pascalCase'
27
- * pascalString2CamelString('PascalCaseTest') // 'pascalCaseTest'
28
- */ const pascalString2CamelString = (str)=>`${str[0].toLowerCase()}${str.slice(1)}`;
29
- /**
30
- * convert PascalCase string to SnakeCase string
31
- * @param str the string to convert
32
- * @example
33
- * pascalString2SnakeString('PascalCase') // 'pascal_case'
34
- * pascalString2SnakeString('PascalCaseTest') // 'pascal_case_test'
35
- */ const pascalString2SnakeString = (str)=>camelString2SnakeString(pascalString2CamelString(str));
36
- /**
37
- * convert SnakeCase string to CamelCase string
38
- * @param str the string to convert
39
- * @example
40
- * snakeString2CamelString('snake_case') // 'snakeCase'
41
- * snakeString2CamelString('snake_case_test') // 'snakeCaseTest'
42
- */ const snakeString2CamelString = (str)=>str.replace(/(_[a-z])/g, (group)=>group.toUpperCase().replace('_', ''));
43
- /**
44
- * convert SnakeCase string to PascalCase string
45
- * @param str the string to convert
46
- * @example
47
- * snakeString2PascalString('snake_case') // 'SnakeCase'
48
- * snakeString2PascalString('snake_case_test') // 'SnakeCaseTest'
49
- */ const snakeString2PascalString = (str)=>camelString2PascalString(snakeString2CamelString(str));
50
- const transformFun = {
51
- CamelToPascal: camelString2PascalString,
52
- CamelToSnake: camelString2SnakeString,
53
- PascalToCamel: pascalString2CamelString,
54
- PascalToSnake: pascalString2SnakeString,
55
- SnakeToCamel: snakeString2CamelString,
56
- SnakeToPascal: snakeString2PascalString
57
- };
58
- const transformObjectKey = (obj, transformFunName)=>{
59
- if (!obj || typeof obj !== 'object') return obj;
60
- if (Array.isArray(obj)) return obj.map((item)=>transformObjectKey(item, transformFunName));
61
- return Object.keys(obj).reduce((acc, key)=>({
62
- ...acc,
63
- [transformFun[transformFunName](key)]: transformObjectKey(obj[key], transformFunName)
64
- }), {});
65
- };
66
- /**
67
- * convert object key from CamelCase to PascalCase
68
- * @param obj the object to convert
69
- * @example
70
- * const obj = {
71
- * fooBar: 'fooBar',
72
- * fooBar2: 'fooBar2',
73
- * fooBar3: {
74
- * fooBar4: 'fooBar4',
75
- * fooBar5: 'fooBar5',
76
- * },
77
- * };
78
- * const result = camelCase2PascalCase(obj);
79
- * console.log(result); // { FooBar: 'fooBar', FooBar2: 'fooBar2', FooBar3: { FooBar4: 'fooBar4', FooBar5: 'fooBar5' } }
80
- */ const camelCase2PascalCase = (obj)=>transformObjectKey(obj, 'CamelToPascal');
81
- /**
82
- * convert object key from CamelCase to SnakeCase
83
- * @param obj the object to convert
84
- * @example
85
- * const obj = {
86
- * fooBar: 'fooBar',
87
- * fooBar2: 'fooBar2',
88
- * fooBar3: {
89
- * fooBar4: 'fooBar4',
90
- * fooBar5: 'fooBar5',
91
- * },
92
- * };
93
- * const result = camelCase2SnakeCase(obj);
94
- * console.log(result); // { foo_bar: 'fooBar', foo_bar2: 'fooBar2', foo_bar3: { foo_bar4: 'fooBar4', foo_bar5: 'fooBar5' } }
95
- */ const camelCase2SnakeCase = (obj)=>transformObjectKey(obj, 'CamelToSnake');
96
- /**
97
- * convert object key from PascalCase to CamelCase
98
- * @param obj the object to convert
99
- * @example
100
- * const obj = {
101
- * FooBar: 'fooBar',
102
- * FooBar2: 'fooBar2',
103
- * FooBar3: {
104
- * FooBar4: 'fooBar4',
105
- * FooBar5: 'fooBar5',
106
- * },
107
- * };
108
- * const result = pascalCase2CamelCase(obj);
109
- * console.log(result); // { fooBar: 'fooBar', fooBar2: 'fooBar2', fooBar3: { fooBar4: 'fooBar4', fooBar5: 'fooBar5' } }
110
- */ const pascalCase2CamelCase = (obj)=>transformObjectKey(obj, 'PascalToCamel');
111
- /**
112
- * convert object key from PascalCase to SnakeCase
113
- * @param obj the object to convert
114
- * @example
115
- * const obj = {
116
- * FooBar: 'fooBar',
117
- * FooBar2: 'fooBar2',
118
- * FooBar3: {
119
- * FooBar4: 'fooBar4',
120
- * FooBar5: 'fooBar5',
121
- * },
122
- * };
123
- * const result = pascalCase2SnakeCase(obj);
124
- * console.log(result); // { foo_bar: 'fooBar', foo_bar2: 'fooBar2', foo_bar3: { foo_bar4: 'fooBar4', foo_bar5: 'fooBar5' } }
125
- */ const pascalCase2SnakeCase = (obj)=>transformObjectKey(obj, 'PascalToSnake');
126
- /**
127
- * convert object key from SnakeCase to CamelCase
128
- * @param obj the object to convert
129
- * @example
130
- * const obj = {
131
- * foo_bar: 'fooBar',
132
- * foo_bar2: 'fooBar2',
133
- * foo_bar3: {
134
- * foo_bar4: 'fooBar4',
135
- * foo_bar5: 'fooBar5',
136
- * },
137
- * };
138
- * const result = snakeCase2CamelCase(obj);
139
- * console.log(result); // { fooBar: 'fooBar', fooBar2: 'fooBar2', fooBar3: { fooBar4: 'fooBar4', fooBar5: 'fooBar5' } }
140
- */ const snakeCase2CamelCase = (obj)=>transformObjectKey(obj, 'SnakeToCamel');
141
- /**
142
- * convert object key from SnakeCase to PascalCase
143
- * @param obj the object to convert
144
- * @example
145
- * const obj = {
146
- * foo_bar: 'fooBar',
147
- * foo_bar2: 'fooBar2',
148
- * foo_bar3: {
149
- * foo_bar4: 'fooBar4',
150
- * foo_bar5: 'fooBar5',
151
- * },
152
- * };
153
- * const result = snakeCase2PascalCase(obj);
154
- * console.log(result); // { FooBar: 'fooBar', FooBar2: 'fooBar2', FooBar3: { FooBar4: 'fooBar4', FooBar5: 'fooBar5' } }
155
- */ const snakeCase2PascalCase = (obj)=>transformObjectKey(obj, 'SnakeToPascal');
156
-
157
- /**
158
- * 檢查稅務編號是否符合正確的編號規則。
159
- *
160
- * @param {string} taxId - 要檢查的8位數稅務編號。
161
- * @returns {boolean} - 如果符合規則則返回 true,否則返回 false。
162
- *
163
- * ### 編號檢查規則:
164
- * 1. **基本格式檢查**:
165
- * - 編號必須為 8 位數字。
166
- * - 不得為「00000000」或「11111111」,這些編號被視為無效。
167
- *
168
- * 2. **驗證邏輯**:
169
- * - 使用一組驗證運算子:`[1, 2, 1, 2, 1, 2, 4, 1]`。
170
- * - 將稅務編號的每一位數字與對應的運算子相乘後,使用 `calculate` 函數計算各位數的和。
171
- * - 計算公式為:`(product % 10) + (product - (product % 10)) / 10`
172
- * - 將所有位數經計算後的結果加總為 `sum`。
173
- *
174
- * 3. **檢查規則**:
175
- * - 如果總和 `sum` 可以被 5 整除,則編號有效。
176
- * - 或者,若第七位數為 7,且 `(sum + 1) % 5 === 0`,則編號有效。
177
- *
178
- * @example
179
- *
180
- * validTaxId('22099131') // true
181
- * validTaxId('84149961') // true
182
- * validTaxId('00000000') // false
183
- * validTaxId('11111111') // false
184
- * validTaxId('22099132') // false
185
- */ const validTaxId = (taxId)=>{
186
- const invalidList = '00000000,11111111';
187
- if (/^\d{8}$/.test(taxId) === false || invalidList.indexOf(taxId) >= 0) {
188
- return false;
20
+ * 代表字節大小的類,提供各種格式化和轉換方法
21
+ */ class ByteSize {
22
+ /**
23
+ * 建立一個新的 ByteSize 實例
24
+ * @param bytes 位元組數值
25
+ */ constructor(bytes){
26
+ this.bytes = bytes;
189
27
  }
190
- const validateOperator = [
191
- 1,
192
- 2,
193
- 1,
194
- 2,
195
- 1,
196
- 2,
197
- 4,
198
- 1
199
- ];
200
- const calculate = (product)=>product % 10 + (product - product % 10) / 10;
201
- const sum = validateOperator.reduce((pre, cur, index)=>pre + calculate(Number(taxId[index]) * cur), 0);
202
- return sum % 5 === 0 || taxId[6] === '7' && (sum + 1) % 5 === 0;
203
- };
28
+ /**
29
+ * 取得原始位元組數值
30
+ */ get value() {
31
+ return this.bytes;
32
+ }
33
+ /**
34
+ * 將位元組轉換為指定單位的數值
35
+ *
36
+ * @param unit 目標單位 (例如 'KB', 'MB', 'GB')
37
+ * @returns 轉換後的數值
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const size = createByteSize(1024);
42
+ * size.to('KB'); // 1
43
+ * size.to('MB'); // 0.0009765625
44
+ * ```
45
+ */ to(unit) {
46
+ if (!FILE_SIZE_UNITS$1.includes(unit)) {
47
+ console.warn(`Invalid unit: ${unit}. Valid units are: ${FILE_SIZE_UNITS$1.join(', ')}`);
48
+ return this.bytes;
49
+ }
50
+ const k = 1024;
51
+ const i = FILE_SIZE_UNITS$1.indexOf(unit);
52
+ return this.bytes / k ** i;
53
+ }
54
+ /**
55
+ * 轉換為適當單位的可讀字符串
56
+ *
57
+ * @param unit 指定單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
58
+ * @param decimals 小數點位數 (預設為 2)
59
+ * @returns 格式化後的字符串
60
+ *
61
+ * @example
62
+ * ```ts
63
+ * const size = createByteSize(1024);
64
+ * size.format(); // '1.00 KB'
65
+ * size.format('KB'); // '1.00 KB'
66
+ * size.format('MB', 3); // '0.001 MB'
67
+ * ```
68
+ */ format(unit, decimals = 2) {
69
+ if (this.bytes === 0) return `0 ${unit || 'Bytes'}`;
70
+ const k = 1024;
71
+ // 如果指定了有效單位,則使用;否則,計算最適合的單位
72
+ const i = unit && FILE_SIZE_UNITS$1.includes(unit) ? FILE_SIZE_UNITS$1.indexOf(unit) : Math.floor(Math.log(this.bytes) / Math.log(k));
73
+ return `${(this.bytes / k ** i).toFixed(decimals)} ${FILE_SIZE_UNITS$1[i]}`;
74
+ }
75
+ /**
76
+ * 比較兩個 ByteSize 實例
77
+ *
78
+ * @param other 要比較的另一個 ByteSize 實例
79
+ * @returns 比較結果:-1 表示小於,0 表示等於,1 表示大於
80
+ */ compareTo(other) {
81
+ if (this.bytes < other.value) return -1;
82
+ if (this.bytes > other.value) return 1;
83
+ return 0;
84
+ }
85
+ /**
86
+ * 轉換為字符串表示
87
+ * @returns 預設格式化的字符串
88
+ */ toString() {
89
+ return this.format();
90
+ }
91
+ }
204
92
  /**
205
- * 驗證日期格式是否正確
206
- *
207
- * @param dateString 日期字串
208
- * @param format 日期格式
209
- * @example
93
+ * 將位元組轉換為可讀字符串 (保留舊的 API 以確保向後兼容)
210
94
  *
211
- * validateDateString('20210201', 'YYYYMMDD') // true
212
- * validateDateString('2021-02-01', 'YYYY-MM-DD') // true
213
- * validateDateString('20210201', 'YYYY-MM-DD') // false
214
- * validateDateString('20210201', 'YYYYMM') // false
215
- */ const validateDateString = (dateString, format)=>{
216
- if (!dateString) return false;
217
- // 根據 format 生成正則表達式
218
- const regexPattern = format.replace(/YYYY/, '\\d{4}').replace(/MM/, '\\d{2}').replace(/DD/, '\\d{2}').replace(/HH/, '\\d{2}').replace(/mm/, '\\d{2}').replace(/ss/, '\\d{2}');
219
- const regex = new RegExp(`^${regexPattern}$`);
220
- // 先用正則驗證格式
221
- if (!regex.test(dateString)) return false;
222
- // 再用 dayjs 驗證是否為有效日期
223
- return dayjs(dateString, format, true).isValid();
224
- };
225
-
226
- /**
227
- * 取得去年今年以及明年期別陣列
95
+ * @param bytes 位元組數值
96
+ * @param unit 目標單位 (例如 'KB', 'MB', 'GB'),不指定則自動選擇最適合的單位
97
+ * @param decimals 小數點位數 (預設為 2)
98
+ * @returns 格式化後的字符串
228
99
  *
229
100
  * @example
230
- * // 假設 今年為 112 年
231
- * generatePeriodArray() // 11102 ~ 11312
232
- */ const generatePeriodArray = ()=>{
233
- const currentYear = new Date().getFullYear() - 1911;
234
- const months = [
235
- '02',
236
- '04',
237
- '06',
238
- '08',
239
- '10',
240
- '12'
241
- ];
242
- const years = [
243
- currentYear - 1,
244
- currentYear,
245
- currentYear + 1
246
- ];
247
- return years.flatMap((year)=>months.map((month)=>`${year}${month}`));
248
- };
101
+ * ```ts
102
+ * convertBytes(0) // '0 Bytes'
103
+ * convertBytes(1024, 'KB') // '1 KB'
104
+ * convertBytes(1024, 'KB', 2) // '1.00 KB'
105
+ * convertBytes(1024 * 1024, 'MB') // '1 MB'
106
+ * convertBytes(1024 * 1024, 'KB') // '1024 KB'
107
+ * ```
108
+ */ const convertBytes = (bytes, unit, decimals = 2)=>new ByteSize(bytes).format(unit, decimals);
109
+
249
110
  /**
250
- * 取得當前期別
111
+ * 檢查兩個值是否相等(包含陣列等引用型別)
112
+ * - 支援基本型別的直接比較
113
+ * - 特別處理空陣列比較
114
+ * - 支援非空陣列的深度比較
251
115
  *
252
- * 報稅期限次期開始15日內
253
- *
254
- * 雙數月沒有特殊規則,期別皆為當月開頭
255
- *
256
- * 單數月15號以前,期別為上個月否則為下個月開頭
116
+ * @param value1 - 第一個值
117
+ * @param value2 - 第二個值
118
+ * @returns 如果值相等則返回 true
257
119
  *
258
120
  * @example
259
- *
260
- * // 假設今天是 111-02-15
261
- * getCurrentPeriod() // 11102
262
- * // 假設今天是 111-02-16
263
- * getCurrentPeriod() // 11102
264
- * // 假設今天是 111-03-15
265
- * getCurrentPeriod() // 11102
266
- * // 假設今天是 111-03-16
267
- * getCurrentPeriod() // 11104
268
- */ const getCurrentPeriod = ()=>{
269
- const now = dayjs();
270
- const currentDate = now.format('DD');
271
- const currentYear = now.format('YYYY');
272
- const currentMonth = now.format('MM');
273
- let endMonth;
274
- if (Number(currentMonth) % 2 === 1) {
275
- endMonth = dayjs(`${currentYear}${currentMonth}`, 'YYYYMM').add(Number(currentDate) <= 15 ? -1 : 1, 'month').format('YYYYMM');
276
- } else {
277
- endMonth = `${currentYear}${currentMonth}`;
121
+ * // 基本型別比較
122
+ * isEqual(1, 1); // true
123
+ * isEqual('abc', 'abc'); // true
124
+ * isEqual(null, null); // true
125
+ *
126
+ * // 陣列比較
127
+ * isEqual([], []); // true
128
+ * isEqual([1, 2], [1, 2]); // true
129
+ * isEqual([1, 2], [1, 3]); // false
130
+ */ const isEqual = (value1, value2)=>{
131
+ // 處理基本型別
132
+ if (value1 === value2) {
133
+ return true;
278
134
  }
279
- return dayjs(endMonth, 'YYYYMM').subtract(1911, 'year').format('YYYYMM').substring(1);
280
- };
281
- /**
282
- * 民國年轉西元年
283
- * @param dateString 日期字串
284
- * @param format 日期格式
285
- * @example
286
- *
287
- * rocEraToAd('1100201') // 20210201
288
- * rocEraToAd('11002', 'YYYYMM') // 202102
289
- */ const rocEraToAd = (dateString, format = 'YYYYMMDD')=>{
290
- if (!validateDateString(`0${dateString}`, format)) return dateString;
291
- return dayjs(`0${dateString}`, format).add(1911, 'year').format(format);
292
- };
293
- /**
294
- * 西元年轉民國年
295
- * @param dateString 日期字串
296
- * @param format 日期格式
297
- * @example
298
- *
299
- * adToRocEra('20210201') // 1100201
300
- * adToRocEra('202102', 'YYYYMM') // 11002
301
- */ const adToRocEra = (dateString, format = 'YYYYMMDD')=>{
302
- if (!validateDateString(dateString, format)) return dateString;
303
- return dayjs(dateString, format).add(-1911, 'year').format(format).substring(1);
135
+ // 處理空陣列
136
+ if (Array.isArray(value1) && Array.isArray(value2) && value1.length === 0 && value2.length === 0) {
137
+ return true;
138
+ }
139
+ // 兩者都是非 null 的物件(包含陣列)
140
+ if (value1 !== null && value2 !== null && typeof value1 === 'object' && typeof value2 === 'object') {
141
+ // 處理非空陣列
142
+ if (Array.isArray(value1) && Array.isArray(value2)) {
143
+ if (value1.length !== value2.length) {
144
+ return false;
145
+ }
146
+ return value1.every((item, index)=>isEqual(item, value2[index]));
147
+ }
148
+ // 未來可以擴展這裡,增加其他物件型別的深度比較
149
+ }
150
+ return false;
304
151
  };
305
152
 
306
153
  /**
@@ -452,50 +299,20 @@ const transformObjectKey = (obj, transformFunName)=>{
452
299
  switch((fileName.split('.').pop() || '').toLocaleLowerCase()){
453
300
  case 'jpeg':
454
301
  case 'jpg':
455
- return 'image/jpeg';
456
- case 'png':
457
- return 'image/png';
458
- case 'pdf':
459
- return 'application/pdf';
460
- case 'zip':
461
- return 'application/zip';
462
- case 'csv':
463
- return 'text/csv';
464
- case 'txt':
465
- return 'text/plain';
466
- default:
467
- return 'application/octet-stream';
468
- }
469
- };
470
-
471
- /**
472
- * A hook to manage a value.
473
- *
474
- * @example
475
- *
476
- * ```tsx
477
- * const MyComponent = ({ value }: { value?: number }) => {
478
- * const [currentValue, setCurrentValue] = useValue({ value });
479
- * };
480
- * ```
481
- */ const useValue = ({ value, defaultValue })=>{
482
- if (value === undefined && defaultValue === undefined) {
483
- throw new Error('Either `value` or `defaultValue` must be provided.');
302
+ return 'image/jpeg';
303
+ case 'png':
304
+ return 'image/png';
305
+ case 'pdf':
306
+ return 'application/pdf';
307
+ case 'zip':
308
+ return 'application/zip';
309
+ case 'csv':
310
+ return 'text/csv';
311
+ case 'txt':
312
+ return 'text/plain';
313
+ default:
314
+ return 'application/octet-stream';
484
315
  }
485
- const isControlled = value !== undefined;
486
- const [internalValue, setInternalValue] = useState(defaultValue);
487
- const setValue = useCallback((newValue)=>{
488
- if (!isControlled) {
489
- setInternalValue(newValue);
490
- }
491
- }, [
492
- isControlled
493
- ]);
494
- const currentValue = isControlled ? value : internalValue;
495
- return [
496
- currentValue,
497
- setValue
498
- ];
499
316
  };
500
317
 
501
318
  // const isProduction: boolean = process.env.NODE_ENV === 'production';
@@ -553,10 +370,12 @@ message) {
553
370
  * @param values 要排除的 value
554
371
  *
555
372
  * @example
556
- * const a = { a: undefined, b: null, c: 3, d: 4 };
557
- * const b = omitByValue(a, undefined, null); // { c: 3, d: 4 }
373
+ * const a = { a: undefined, b: null, c: 3, d: 4, e: [] };
374
+ * const b = omitByValue(a, undefined, null, []); // { c: 3, d: 4 }
558
375
  */ const omitByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
559
- if (values.includes(value)) {
376
+ // 使用深度比較檢查值是否應該被排除
377
+ const shouldOmit = values.some((excludeValue)=>isEqual(value, excludeValue));
378
+ if (shouldOmit) {
560
379
  return acc;
561
380
  }
562
381
  return {
@@ -586,10 +405,12 @@ message) {
586
405
  *
587
406
  * @example
588
407
  *
589
- * const a = { a: 1, b: 2, c: 3, d: 4 };
590
- * const b = pickByValue(a, 1, 2); // { a: 1, b: 2 }
408
+ * const a = { a: 1, b: 2, c: 3, d: 4, e: [] };
409
+ * const b = pickByValue(a, 1, 2, []); // { a: 1, b: 2, e: [] }
591
410
  */ const pickByValue = (object, ...values)=>Object.entries(object).reduce((acc, [key, value])=>{
592
- if (values.includes(value)) {
411
+ // 使用深度比較檢查值是否應該被選擇
412
+ const shouldPick = values.some((pickValue)=>isEqual(value, pickValue));
413
+ if (shouldPick) {
593
414
  return {
594
415
  ...acc,
595
416
  [key]: value
@@ -657,44 +478,344 @@ const isObject = (value)=>value !== null && typeof value === 'object';
657
478
  };
658
479
  };
659
480
  /**
660
- * throttle function
481
+ * throttle function
482
+ *
483
+ * @param {Function} fn function to be executed
484
+ * @param {number} delay time to wait before executing the function
485
+ *
486
+ * @example
487
+ * const throttledFunction = throttle((a: number, b: number) => a + b, 1000);
488
+ * throttledFunction(1, 2); // 3
489
+ * throttledFunction(3, 4); // undefined
490
+ * setTimeout(() => {
491
+ * throttledFunction(5, 6); // 11
492
+ * }, 2000);
493
+ */ const throttle = (fn, delay)=>{
494
+ let wait = false;
495
+ return (...args)=>{
496
+ if (wait) return undefined;
497
+ const val = fn(...args);
498
+ wait = true;
499
+ setTimeout(()=>{
500
+ wait = false;
501
+ }, delay);
502
+ return val;
503
+ };
504
+ };
505
+
506
+ /**
507
+ * Wait for a given amount of time
508
+ * @param ms time to wait in milliseconds
509
+ */ const wait = (ms)=>{
510
+ };
511
+
512
+ /**
513
+ * 將單層物件轉換為 URLSearchParams 物件
514
+ * - 會自動排除 null、undefined、空字串和空陣列的值
515
+ * - 陣列會以逗號連接為字串
516
+ *
517
+ * @param obj - 要轉換的物件,只支援單層物件,其中值可以是 string、number、boolean、null、undefined 或字串陣列
518
+ * @returns URLSearchParams 實例
519
+ *
520
+ * @example
521
+ * const params = { a: '1', b: 123, c: false, d: ['1','2'], e: null, f: undefined, g: '', h: [] };
522
+ * objectToSearchParams(params).toString(); // 'a=1&b=123&c=false&d=1%2C2'
523
+ */ const objectToSearchParams = (obj)=>{
524
+ const searchParams = new URLSearchParams();
525
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
526
+ return searchParams;
527
+ }
528
+ Object.entries(omitByValue(obj, undefined, null, '', [])).forEach(([key, value])=>{
529
+ // 如果是陣列,則以逗號連接
530
+ const paramValue = Array.isArray(value) ? value.join(',') : String(value);
531
+ searchParams.append(key, paramValue);
532
+ });
533
+ return searchParams;
534
+ };
535
+ /**
536
+ * 將字串值轉換為指定的型別
537
+ *
538
+ * @param value - 要轉換的字串值
539
+ * @param targetType - 目標型別
540
+ * @returns 轉換後的值
541
+ */ const convertValueByType = (value, targetType)=>{
542
+ switch(targetType){
543
+ case 'number':
544
+ return value ? Number(value) : 0;
545
+ case 'boolean':
546
+ return value === 'true' || value === '1';
547
+ case 'array':
548
+ return value ? value.split(',') : [];
549
+ case 'string':
550
+ default:
551
+ // 預設為字串,不需要轉換
552
+ return value;
553
+ }
554
+ };
555
+ /**
556
+ * 將 URLSearchParams 或字串轉換為物件
557
+ *
558
+ * @param searchParams - 要轉換的搜尋參數字串或 URLSearchParams 實例
559
+ * @param typeMap - 可選的型別轉換映射表,用於指定每個參數的目標型別
560
+ * @returns
561
+ *
562
+ * @example
563
+ * const queryString = 'a=1&b=123&c=true&d=1,2,3&e=false';
564
+ * const result = searchParamsToObject(queryString);
565
+ * // result: { a: '1', b: '123', c: 'true', d: '1,2,3', e: 'false' }
566
+ * const result = searchParamsToObject(queryString, {
567
+ * a: 'string',
568
+ * b: 'number',
569
+ * c: 'boolean',
570
+ * d: 'array',
571
+ * e: 'boolean',
572
+ * });
573
+ * // result: { a: '1', b: 123, c: true, d: ['1', '2', '3'], e: false }
574
+ */ const searchParamsToObject = (searchParams, typeMap = {})=>{
575
+ const searchParamsInstance = typeof searchParams === 'string' ? new URLSearchParams(searchParams) : searchParams;
576
+ const result = {};
577
+ // 從 URLSearchParams 取得所有參數
578
+ searchParamsInstance.forEach((value, key)=>{
579
+ if (!key) {
580
+ return;
581
+ }
582
+ const targetType = typeMap[key];
583
+ result[key] = convertValueByType(value, targetType);
584
+ });
585
+ return result;
586
+ };
587
+
588
+ /**
589
+ * convert CamelCase string to PascalCase string
590
+ * @param str the string to convert
591
+ * @example
592
+ * camelString2PascalString('camelCase') // 'CamelCase'
593
+ * camelString2PascalString('camelCaseTest') // 'CamelCaseTest'
594
+ */ const camelString2PascalString = (str)=>`${str[0].toUpperCase()}${str.slice(1)}`;
595
+ /**
596
+ * convert CamelCase string to SnakeCase string
597
+ * @param str the string to convert
598
+ * @example
599
+ * camelString2SnakeString('camelCase') // 'camel_case'
600
+ * camelString2SnakeString('camelCaseTest') // 'camel_case_test'
601
+ */ const camelString2SnakeString = (str)=>str.replace(/[A-Z]/g, (letter)=>`_${letter.toLowerCase()}`);
602
+ /**
603
+ * convert PascalCase string to CamelCase string
604
+ * @param str the string to convert
605
+ * @example
606
+ * pascalString2CamelString('PascalCase') // 'pascalCase'
607
+ * pascalString2CamelString('PascalCaseTest') // 'pascalCaseTest'
608
+ */ const pascalString2CamelString = (str)=>`${str[0].toLowerCase()}${str.slice(1)}`;
609
+ /**
610
+ * convert PascalCase string to SnakeCase string
611
+ * @param str the string to convert
612
+ * @example
613
+ * pascalString2SnakeString('PascalCase') // 'pascal_case'
614
+ * pascalString2SnakeString('PascalCaseTest') // 'pascal_case_test'
615
+ */ const pascalString2SnakeString = (str)=>camelString2SnakeString(pascalString2CamelString(str));
616
+ /**
617
+ * convert SnakeCase string to CamelCase string
618
+ * @param str the string to convert
619
+ * @example
620
+ * snakeString2CamelString('snake_case') // 'snakeCase'
621
+ * snakeString2CamelString('snake_case_test') // 'snakeCaseTest'
622
+ */ const snakeString2CamelString = (str)=>str.replace(/(_[a-z])/g, (group)=>group.toUpperCase().replace('_', ''));
623
+ /**
624
+ * convert SnakeCase string to PascalCase string
625
+ * @param str the string to convert
626
+ * @example
627
+ * snakeString2PascalString('snake_case') // 'SnakeCase'
628
+ * snakeString2PascalString('snake_case_test') // 'SnakeCaseTest'
629
+ */ const snakeString2PascalString = (str)=>camelString2PascalString(snakeString2CamelString(str));
630
+ const transformFun = {
631
+ CamelToPascal: camelString2PascalString,
632
+ CamelToSnake: camelString2SnakeString,
633
+ PascalToCamel: pascalString2CamelString,
634
+ PascalToSnake: pascalString2SnakeString,
635
+ SnakeToCamel: snakeString2CamelString,
636
+ SnakeToPascal: snakeString2PascalString
637
+ };
638
+ const transformObjectKey = (obj, transformFunName)=>{
639
+ if (!obj || typeof obj !== 'object') return obj;
640
+ if (Array.isArray(obj)) return obj.map((item)=>transformObjectKey(item, transformFunName));
641
+ return Object.keys(obj).reduce((acc, key)=>({
642
+ ...acc,
643
+ [transformFun[transformFunName](key)]: transformObjectKey(obj[key], transformFunName)
644
+ }), {});
645
+ };
646
+ /**
647
+ * convert object key from CamelCase to PascalCase
648
+ * @param obj the object to convert
649
+ * @example
650
+ * const obj = {
651
+ * fooBar: 'fooBar',
652
+ * fooBar2: 'fooBar2',
653
+ * fooBar3: {
654
+ * fooBar4: 'fooBar4',
655
+ * fooBar5: 'fooBar5',
656
+ * },
657
+ * };
658
+ * const result = camelCase2PascalCase(obj);
659
+ * console.log(result); // { FooBar: 'fooBar', FooBar2: 'fooBar2', FooBar3: { FooBar4: 'fooBar4', FooBar5: 'fooBar5' } }
660
+ */ const camelCase2PascalCase = (obj)=>transformObjectKey(obj, 'CamelToPascal');
661
+ /**
662
+ * convert object key from CamelCase to SnakeCase
663
+ * @param obj the object to convert
664
+ * @example
665
+ * const obj = {
666
+ * fooBar: 'fooBar',
667
+ * fooBar2: 'fooBar2',
668
+ * fooBar3: {
669
+ * fooBar4: 'fooBar4',
670
+ * fooBar5: 'fooBar5',
671
+ * },
672
+ * };
673
+ * const result = camelCase2SnakeCase(obj);
674
+ * console.log(result); // { foo_bar: 'fooBar', foo_bar2: 'fooBar2', foo_bar3: { foo_bar4: 'fooBar4', foo_bar5: 'fooBar5' } }
675
+ */ const camelCase2SnakeCase = (obj)=>transformObjectKey(obj, 'CamelToSnake');
676
+ /**
677
+ * convert object key from PascalCase to CamelCase
678
+ * @param obj the object to convert
679
+ * @example
680
+ * const obj = {
681
+ * FooBar: 'fooBar',
682
+ * FooBar2: 'fooBar2',
683
+ * FooBar3: {
684
+ * FooBar4: 'fooBar4',
685
+ * FooBar5: 'fooBar5',
686
+ * },
687
+ * };
688
+ * const result = pascalCase2CamelCase(obj);
689
+ * console.log(result); // { fooBar: 'fooBar', fooBar2: 'fooBar2', fooBar3: { fooBar4: 'fooBar4', fooBar5: 'fooBar5' } }
690
+ */ const pascalCase2CamelCase = (obj)=>transformObjectKey(obj, 'PascalToCamel');
691
+ /**
692
+ * convert object key from PascalCase to SnakeCase
693
+ * @param obj the object to convert
694
+ * @example
695
+ * const obj = {
696
+ * FooBar: 'fooBar',
697
+ * FooBar2: 'fooBar2',
698
+ * FooBar3: {
699
+ * FooBar4: 'fooBar4',
700
+ * FooBar5: 'fooBar5',
701
+ * },
702
+ * };
703
+ * const result = pascalCase2SnakeCase(obj);
704
+ * console.log(result); // { foo_bar: 'fooBar', foo_bar2: 'fooBar2', foo_bar3: { foo_bar4: 'fooBar4', foo_bar5: 'fooBar5' } }
705
+ */ const pascalCase2SnakeCase = (obj)=>transformObjectKey(obj, 'PascalToSnake');
706
+ /**
707
+ * convert object key from SnakeCase to CamelCase
708
+ * @param obj the object to convert
709
+ * @example
710
+ * const obj = {
711
+ * foo_bar: 'fooBar',
712
+ * foo_bar2: 'fooBar2',
713
+ * foo_bar3: {
714
+ * foo_bar4: 'fooBar4',
715
+ * foo_bar5: 'fooBar5',
716
+ * },
717
+ * };
718
+ * const result = snakeCase2CamelCase(obj);
719
+ * console.log(result); // { fooBar: 'fooBar', fooBar2: 'fooBar2', fooBar3: { fooBar4: 'fooBar4', fooBar5: 'fooBar5' } }
720
+ */ const snakeCase2CamelCase = (obj)=>transformObjectKey(obj, 'SnakeToCamel');
721
+ /**
722
+ * convert object key from SnakeCase to PascalCase
723
+ * @param obj the object to convert
724
+ * @example
725
+ * const obj = {
726
+ * foo_bar: 'fooBar',
727
+ * foo_bar2: 'fooBar2',
728
+ * foo_bar3: {
729
+ * foo_bar4: 'fooBar4',
730
+ * foo_bar5: 'fooBar5',
731
+ * },
732
+ * };
733
+ * const result = snakeCase2PascalCase(obj);
734
+ * console.log(result); // { FooBar: 'fooBar', FooBar2: 'fooBar2', FooBar3: { FooBar4: 'fooBar4', FooBar5: 'fooBar5' } }
735
+ */ const snakeCase2PascalCase = (obj)=>transformObjectKey(obj, 'SnakeToPascal');
736
+
737
+ /**
738
+ * 將數字轉換成金額千分位格式
739
+ *
740
+ * @param num - 數字
741
+ *
742
+ * @example
743
+ *
744
+ * formatAmount(1234567) // '1,234,567'
745
+ */ const formatAmount = (num)=>{
746
+ if (typeof num !== 'number') return '';
747
+ return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
748
+ };
749
+ /**
750
+ * 將字串的第 n - m 個字轉換成星號
751
+ *
752
+ * @param str - 字串
753
+ * @param n - 起始位置
754
+ * @param m - 結束位置
755
+ *
756
+ * @example
757
+ *
758
+ * formatString('123456', 1, 4) // '1****6'
759
+ *
760
+ * @deprecated use `maskString` instead
761
+ */ const formatStarMask = (str, n, m)=>str.slice(0, n) + '*'.repeat(m - n + 1) + str.slice(m + 1);
762
+ /**
763
+ * 將字串的指定位置的以後的字元轉換成星號
764
+ *
765
+ * @param str 字串
766
+ * @param start 起始位置 (從 0 開始計算)
767
+ * @param length 可選,從起始位置開始要遮罩的字元數量,默認為剩餘所有字元
768
+ *
769
+ * @example
770
+ *
771
+ * ```js
772
+ * maskString('123456789', 2) // '12*******'
773
+ * maskString('123456789', 2, 5) // '12*****89'
774
+ * maskString('123456789', 0, 15) // '*********'
775
+ * maskString('123456789', 10) // '123456789' (start out of bounds)
776
+ * maskString('123456789', -1) // '123456789' (start out of bounds)
777
+ * ```
778
+ */ const maskString = (str, start, length)=>{
779
+ if (start < 0 || start >= str.length) return str;
780
+ const maxMaskLength = str.length - start;
781
+ const safeLength = length !== undefined ? Math.max(0, Math.min(length, maxMaskLength)) : maxMaskLength;
782
+ return str.slice(0, start) + '*'.repeat(safeLength) + str.slice(start + safeLength);
783
+ };
784
+ const FILE_SIZE_UNITS = [
785
+ 'Bytes',
786
+ 'KB',
787
+ 'MB',
788
+ 'GB',
789
+ 'TB',
790
+ 'PB',
791
+ 'EB',
792
+ 'ZB',
793
+ 'YB'
794
+ ];
795
+ /**
796
+ * format file size to human readable string
661
797
  *
662
- * @param {Function} fn function to be executed
663
- * @param {number} delay time to wait before executing the function
798
+ * it will convert bytes to KB, MB, GB, TB, PB, EB, ZB, YB
799
+ *
800
+ * @param bytes file size in bytes
801
+ * @param decimals number of decimal places (default is 2)
664
802
  *
665
803
  * @example
666
- * const throttledFunction = throttle((a: number, b: number) => a + b, 1000);
667
- * throttledFunction(1, 2); // 3
668
- * throttledFunction(3, 4); // undefined
669
- * setTimeout(() => {
670
- * throttledFunction(5, 6); // 11
671
- * }, 2000);
672
- */ const throttle = (fn, delay)=>{
673
- let wait = false;
674
- return (...args)=>{
675
- if (wait) return undefined;
676
- const val = fn(...args);
677
- wait = true;
678
- setTimeout(()=>{
679
- wait = false;
680
- }, delay);
681
- return val;
682
- };
804
+ *
805
+ * ```js
806
+ * formatBytes(0) // 0 Bytes
807
+ * formatBytes(1024) // 1 KB
808
+ * formatBytes(1024, 2) // 1.00 KB
809
+ * formatBytes(1024 * 1024) // 1 MB
810
+ * ```
811
+ * @deprecated use `convertBytes` instead
812
+ */ const formatBytes = (bytes, decimals = 0)=>{
813
+ if (bytes === 0) return '0 Bytes';
814
+ const k = 1024;
815
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
816
+ return `${(bytes / k ** i).toFixed(decimals)} ${FILE_SIZE_UNITS[i]}`;
683
817
  };
684
818
 
685
- function mergeRefs(refs) {
686
- return (value)=>{
687
- refs.forEach((ref)=>{
688
- if (typeof ref === 'function') {
689
- ref(value);
690
- } else if (ref != null) {
691
- // eslint-disable-next-line no-param-reassign
692
- ref.current = value;
693
- }
694
- });
695
- };
696
- }
697
-
698
819
  /**
699
820
  * 中文
700
821
  *
@@ -863,66 +984,196 @@ function mergeRefs(refs) {
863
984
  */ const isTWPhone = ()=>/^(((0[2-9]-?\d{6,8})(#\d{1,5})?)|((0[2-9][0-9]-?\d{6,7})(#\d{1,5})?))$/;
864
985
 
865
986
  /**
866
- * 將數字轉換成金額千分位格式
987
+ * 檢查稅務編號是否符合正確的編號規則。
867
988
  *
868
- * @param num - 數字
989
+ * @param {string} taxId - 要檢查的8位數稅務編號。
990
+ * @returns {boolean} - 如果符合規則則返回 true,否則返回 false。
869
991
  *
870
- * @example
992
+ * ### 編號檢查規則:
993
+ * 1. **基本格式檢查**:
994
+ * - 編號必須為 8 位數字。
995
+ * - 不得為「00000000」或「11111111」,這些編號被視為無效。
871
996
  *
872
- * formatAmount(1234567) // '1,234,567'
873
- */ const formatAmount = (num)=>{
874
- if (typeof num !== 'number') return '';
875
- return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
876
- };
877
- /**
878
- * 將字串的第 n - m 個字轉換成星號
997
+ * 2. **驗證邏輯**:
998
+ * - 使用一組驗證運算子:`[1, 2, 1, 2, 1, 2, 4, 1]`。
999
+ * - 將稅務編號的每一位數字與對應的運算子相乘後,使用 `calculate` 函數計算各位數的和。
1000
+ * - 計算公式為:`(product % 10) + (product - (product % 10)) / 10`
1001
+ * - 將所有位數經計算後的結果加總為 `sum`。
879
1002
  *
880
- * @param str - 字串
881
- * @param n - 起始位置
882
- * @param m - 結束位置
1003
+ * 3. **檢查規則**:
1004
+ * - 如果總和 `sum` 可以被 5 整除,則編號有效。
1005
+ * - 或者,若第七位數為 7,且 `(sum + 1) % 5 === 0`,則編號有效。
883
1006
  *
884
1007
  * @example
885
1008
  *
886
- * formatString('123456', 1, 4) // '1****6'
887
- */ const formatStarMask = (str, n, m)=>str.slice(0, n) + '*'.repeat(m - n + 1) + str.slice(m + 1);
1009
+ * validTaxId('22099131') // true
1010
+ * validTaxId('84149961') // true
1011
+ * validTaxId('00000000') // false
1012
+ * validTaxId('11111111') // false
1013
+ * validTaxId('22099132') // false
1014
+ */ const validTaxId = (taxId)=>{
1015
+ const invalidList = '00000000,11111111';
1016
+ if (/^\d{8}$/.test(taxId) === false || invalidList.indexOf(taxId) >= 0) {
1017
+ return false;
1018
+ }
1019
+ const validateOperator = [
1020
+ 1,
1021
+ 2,
1022
+ 1,
1023
+ 2,
1024
+ 1,
1025
+ 2,
1026
+ 4,
1027
+ 1
1028
+ ];
1029
+ const calculate = (product)=>product % 10 + (product - product % 10) / 10;
1030
+ const sum = validateOperator.reduce((pre, cur, index)=>pre + calculate(Number(taxId[index]) * cur), 0);
1031
+ return sum % 5 === 0 || taxId[6] === '7' && (sum + 1) % 5 === 0;
1032
+ };
888
1033
  /**
889
- * format file size to human readable string
1034
+ * 驗證日期格式是否正確
890
1035
  *
891
- * it will convert bytes to KB, MB, GB, TB, PB, EB, ZB, YB
1036
+ * @param dateString 日期字串
1037
+ * @param format 日期格式
1038
+ * @example
892
1039
  *
893
- * @param bytes file size in bytes
894
- * @param decimals number of decimal places (default is 2)
1040
+ * validateDateString('20210201', 'YYYYMMDD') // true
1041
+ * validateDateString('2021-02-01', 'YYYY-MM-DD') // true
1042
+ * validateDateString('20210201', 'YYYY-MM-DD') // false
1043
+ * validateDateString('20210201', 'YYYYMM') // false
1044
+ */ const validateDateString = (dateString, format)=>{
1045
+ if (!dateString) return false;
1046
+ // 根據 format 生成正則表達式
1047
+ const regexPattern = format.replace(/YYYY/, '\\d{4}').replace(/MM/, '\\d{2}').replace(/DD/, '\\d{2}').replace(/HH/, '\\d{2}').replace(/mm/, '\\d{2}').replace(/ss/, '\\d{2}');
1048
+ const regex = new RegExp(`^${regexPattern}$`);
1049
+ // 先用正則驗證格式
1050
+ if (!regex.test(dateString)) return false;
1051
+ // 再用 dayjs 驗證是否為有效日期
1052
+ return dayjs(dateString, format, true).isValid();
1053
+ };
1054
+
1055
+ /**
1056
+ * A hook to manage a value.
895
1057
  *
896
1058
  * @example
897
1059
  *
898
- * ```js
899
- * formatBytes(0) // 0 Bytes
900
- * formatBytes(1024) // 1 KB
901
- * formatBytes(1024, 2) // 1.00 KB
902
- * formatBytes(1024 * 1024) // 1 MB
1060
+ * ```tsx
1061
+ * const MyComponent = ({ value }: { value?: number }) => {
1062
+ * const [currentValue, setCurrentValue] = useValue({ value });
1063
+ * };
903
1064
  * ```
904
- */ const formatBytes = (bytes, decimals = 0)=>{
905
- if (bytes === 0) return '0 Bytes';
906
- const k = 1024;
907
- const sizes = [
908
- 'Bytes',
909
- 'KB',
910
- 'MB',
911
- 'GB',
912
- 'TB',
913
- 'PB',
914
- 'EB',
915
- 'ZB',
916
- 'YB'
1065
+ */ const useValue = ({ value, defaultValue })=>{
1066
+ if (value === undefined && defaultValue === undefined) {
1067
+ throw new Error('Either `value` or `defaultValue` must be provided.');
1068
+ }
1069
+ const isControlled = value !== undefined;
1070
+ const [internalValue, setInternalValue] = useState(defaultValue);
1071
+ const setValue = useCallback((newValue)=>{
1072
+ if (!isControlled) {
1073
+ setInternalValue(newValue);
1074
+ }
1075
+ }, [
1076
+ isControlled
1077
+ ]);
1078
+ const currentValue = isControlled ? value : internalValue;
1079
+ return [
1080
+ currentValue,
1081
+ setValue
917
1082
  ];
918
- const i = Math.floor(Math.log(bytes) / Math.log(k));
919
- return `${(bytes / k ** i).toFixed(decimals)} ${sizes[i]}`;
920
1083
  };
921
1084
 
1085
+ function mergeRefs(refs) {
1086
+ return (value)=>{
1087
+ refs.forEach((ref)=>{
1088
+ if (typeof ref === 'function') {
1089
+ ref(value);
1090
+ } else if (ref != null) {
1091
+ // eslint-disable-next-line no-param-reassign
1092
+ ref.current = value;
1093
+ }
1094
+ });
1095
+ };
1096
+ }
1097
+
922
1098
  /**
923
- * Wait for a given amount of time
924
- * @param ms time to wait in milliseconds
925
- */ const wait = (ms)=>{
1099
+ * 民國年轉西元年
1100
+ * @param dateString 日期字串
1101
+ * @param format 日期格式
1102
+ * @example
1103
+ *
1104
+ * rocEraToAd('1100201') // 20210201
1105
+ * rocEraToAd('11002', 'YYYYMM') // 202102
1106
+ */ const rocEraToAd = (dateString, format = 'YYYYMMDD')=>{
1107
+ if (!validateDateString(`0${dateString}`, format)) return dateString;
1108
+ return dayjs(`0${dateString}`, format).add(1911, 'year').format(format);
1109
+ };
1110
+ /**
1111
+ * 西元年轉民國年
1112
+ * @param dateString 日期字串
1113
+ * @param format 日期格式
1114
+ * @example
1115
+ *
1116
+ * adToRocEra('20210201') // 1100201
1117
+ * adToRocEra('202102', 'YYYYMM') // 11002
1118
+ */ const adToRocEra = (dateString, format = 'YYYYMMDD')=>{
1119
+ if (!validateDateString(dateString, format)) return dateString;
1120
+ return dayjs(dateString, format).add(-1911, 'year').format(format).substring(1);
1121
+ };
1122
+
1123
+ /**
1124
+ * 取得去年今年以及明年期別陣列
1125
+ *
1126
+ * @example
1127
+ * // 假設 今年為 112 年
1128
+ * generatePeriodArray() // 11102 ~ 11312
1129
+ */ const generatePeriodArray = ()=>{
1130
+ const currentYear = new Date().getFullYear() - 1911;
1131
+ const months = [
1132
+ '02',
1133
+ '04',
1134
+ '06',
1135
+ '08',
1136
+ '10',
1137
+ '12'
1138
+ ];
1139
+ const years = [
1140
+ currentYear - 1,
1141
+ currentYear,
1142
+ currentYear + 1
1143
+ ];
1144
+ return years.flatMap((year)=>months.map((month)=>`${year}${month}`));
1145
+ };
1146
+ /**
1147
+ * 取得當前期別
1148
+ *
1149
+ * 報稅期限次期開始15日內
1150
+ *
1151
+ * 雙數月沒有特殊規則,期別皆為當月開頭
1152
+ *
1153
+ * 單數月15號以前,期別為上個月否則為下個月開頭
1154
+ *
1155
+ * @example
1156
+ *
1157
+ * // 假設今天是 111-02-15
1158
+ * getCurrentPeriod() // 11102
1159
+ * // 假設今天是 111-02-16
1160
+ * getCurrentPeriod() // 11102
1161
+ * // 假設今天是 111-03-15
1162
+ * getCurrentPeriod() // 11102
1163
+ * // 假設今天是 111-03-16
1164
+ * getCurrentPeriod() // 11104
1165
+ */ const getCurrentPeriod = ()=>{
1166
+ const now = dayjs();
1167
+ const currentDate = now.format('DD');
1168
+ const currentYear = now.format('YYYY');
1169
+ const currentMonth = now.format('MM');
1170
+ let endMonth;
1171
+ if (Number(currentMonth) % 2 === 1) {
1172
+ endMonth = dayjs(`${currentYear}${currentMonth}`, 'YYYYMM').add(Number(currentDate) <= 15 ? -1 : 1, 'month').format('YYYYMM');
1173
+ } else {
1174
+ endMonth = `${currentYear}${currentMonth}`;
1175
+ }
1176
+ return dayjs(endMonth, 'YYYYMM').subtract(1911, 'year').format('YYYYMM').substring(1);
926
1177
  };
927
1178
 
928
- export { adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, createEnumLikeObject, debounce, deepMerge, extractEnumLikeObject, fakeApi, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, getMimeType, invariant, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isServer, isTWMobile, isTWPhone, isTimeString, isValidPassword, mergeRefs, omit, omitByValue, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, pick, pickByValue, rocEraToAd, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, throttle, useValue, validTaxId, validateDateString, validateFileType, wait };
1179
+ export { ByteSize, adToRocEra, camelCase2PascalCase, camelCase2SnakeCase, camelString2PascalString, camelString2SnakeString, convertBytes, createEnumLikeObject, debounce, deepMerge, extractEnumLikeObject, fakeApi, formatAmount, formatBytes, formatStarMask, generatePeriodArray, getCurrentPeriod, getMimeType, invariant, isChinese, isDateString, isDateTimeString, isEmail, isEnglish, isEqual, isNonZeroStart, isNumber, isNumberAtLeastN, isNumberN, isNumberNM, isServer, isTWMobile, isTWPhone, isTimeString, isValidPassword, maskString, mergeRefs, objectToSearchParams, omit, omitByValue, pascalCase2CamelCase, pascalCase2SnakeCase, pascalString2CamelString, pascalString2SnakeString, pick, pickByValue, rocEraToAd, searchParamsToObject, snakeCase2CamelCase, snakeCase2PascalCase, snakeString2CamelString, snakeString2PascalString, throttle, useValue, validTaxId, validateDateString, validateFileType, wait };