@ntnyq/utils 0.9.1 → 0.10.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/index.d.ts CHANGED
@@ -9,6 +9,22 @@ declare function noop(): void;
9
9
  declare const NOOP: typeof noop;
10
10
  //#endregion
11
11
  //#region src/fn/once.d.ts
12
+ /**
13
+ * Creates a function that is restricted to invoking `func` once. Repeat calls to the function return `false`.
14
+ *
15
+ * @param func - The function to restrict.
16
+ * @returns A new function that returns `true` when `func` is invoked for the first time and `false` on subsequent calls.
17
+ *
18
+ * @example
19
+ *
20
+ * ```ts
21
+ * const initialize = once(() => {
22
+ * console.log('Initialized')
23
+ * })
24
+ *
25
+ * initialize() // Logs: 'Initialized', returns true
26
+ * ```
27
+ */
12
28
  declare function once<T extends unknown[]>(func: (...args: T) => void): (this: unknown, ...args: T) => boolean;
13
29
  //#endregion
14
30
  //#region src/is/dom.d.ts
@@ -65,6 +81,13 @@ declare function isError(value: unknown): value is Error;
65
81
  declare function isNativePromise<T = unknown>(value: unknown): value is Promise<T>;
66
82
  declare function isPromise<T = unknown>(value: unknown): value is Promise<T>;
67
83
  declare function isIterable<T = unknown>(value: unknown): value is Iterable<T>;
84
+ declare function isBlob(value: unknown): value is Blob;
85
+ declare function isFormData(value: unknown): value is FormData;
86
+ declare function isFile(value: unknown): value is File;
87
+ type UrlString = string & {
88
+ readonly __brand: "UrlString";
89
+ };
90
+ declare function isUrlString(value: unknown): value is UrlString;
68
91
  //#endregion
69
92
  //#region src/is/isDeepEqual.d.ts
70
93
  /**
@@ -97,7 +120,7 @@ type Nullable<T> = T | null;
97
120
  /**
98
121
  * Overwrite some keys type
99
122
  */
100
- type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
123
+ type Overwrite<T, U$1> = Pick<T, Exclude<keyof T, keyof U$1>> & U$1;
101
124
  /**
102
125
  * Prettify object type
103
126
  */
@@ -129,7 +152,7 @@ type LiteralUnion<Union extends Base, Base = string> = Union | (Base & {
129
152
  /**
130
153
  * @see {@link TODO:}
131
154
  */
132
- type Merge<T, U> = keyof T & keyof U extends never ? T & U : Omit<T, keyof T & keyof U> & U;
155
+ type Merge<T, U$1> = keyof T & keyof U$1 extends never ? T & U$1 : Omit<T, keyof T & keyof U$1> & U$1;
133
156
  /**
134
157
  * Non empty object `{}`
135
158
  */
@@ -586,7 +609,7 @@ declare function interopDefault<T>(mod: Awaitable<T>): Promise<InteropModuleDefa
586
609
  * // => {}
587
610
  * ```
588
611
  */
589
- declare function resolveSubOptions<T extends Record<string, any>, K extends keyof T>(options: T, key: K): Partial<ResolvedOptions<T[K]>>;
612
+ declare function resolveSubOptions<T extends Record<string, any>, K$1 extends keyof T>(options: T, key: K$1): Partial<ResolvedOptions<T[K$1]>>;
590
613
  //#endregion
591
614
  //#region src/number/random.d.ts
592
615
  interface RamdomNumberOptions {
@@ -648,10 +671,10 @@ interface ToIntegerOptions {
648
671
  declare function toInteger(value: unknown, options?: ToIntegerOptions): number;
649
672
  //#endregion
650
673
  //#region src/object/omit.d.ts
651
- declare function omit<T, K extends keyof T>(object: T, ...keys: K[]): Omit<T, K>;
674
+ declare function omit<T, K$1 extends keyof T>(object: T, ...keys: K$1[]): Omit<T, K$1>;
652
675
  //#endregion
653
676
  //#region src/object/pick.d.ts
654
- declare function pick<T, K extends keyof T>(object: T, keys: K[]): Pick<T, K>;
677
+ declare function pick<T, K$1 extends keyof T>(object: T, keys: K$1[]): Pick<T, K$1>;
655
678
  //#endregion
656
679
  //#region src/object/clean.d.ts
657
680
  interface CleanObjectOptions {
@@ -838,7 +861,30 @@ declare function getStringSimilarity(str1: string, str2: string, options?: GetSt
838
861
  * Special chars
839
862
  */
840
863
  declare const SPECIAL_CHAR: {
864
+ /**
865
+ * 中文顿号
866
+ */
867
+ chineseComma: string;
868
+ /**
869
+ * 英文逗号
870
+ */
871
+ englishComma: string;
872
+ /**
873
+ * 英文句号
874
+ */
875
+ englishPeriod: string;
876
+ /**
877
+ * 连接符
878
+ */
879
+ hyphen: string;
880
+ /**
881
+ * 换行
882
+ */
841
883
  newline: string;
884
+ /**
885
+ * 空格
886
+ */
887
+ whitespace: string;
842
888
  };
843
889
  //#endregion
844
890
  //#region src/constants/regexp.d.ts
@@ -857,4 +903,4 @@ declare const RE_LINE_COMMENT: RegExp;
857
903
  */
858
904
  declare const RE_BLOCK_COMMENT: RegExp;
859
905
  //#endregion
860
- export { AnyFn, Arrayable, Awaitable, Callable, CleanObjectOptions, Color, CreatePadStringOptions, DeepRequired, ElementOf, GetStringSimilarityOptions, InteropModuleDefault, JsonArray, JsonObject, JsonPrimitive, JsonValue, LiteralUnion, MayBe, Merge, NOOP, NonEmptyObject, NonEmptyString, Nullable, OpenExternalURLOptions, Overwrite, Prettify, PrettifyV2, Primitive, RE_BLOCK_COMMENT, RE_COMMENTS, RE_LINE_COMMENT, RamdomNumberOptions, ResolvedOptions, SPECIAL_CHAR, STORAGE_UNITS, SortObjectOptions, StorageUnit, TIME_UNITS, ThrottleDebounceOptions, TimeUnit, ToIntegerOptions, ValueOf, Whitespace, at, cAF, chunk, clamp, cleanObject, convertFromBytes, convertFromMilliseconds, convertStorageUnit, convertTimeUnit, convertToBytes, convertToMilliseconds, createPadString, debounce, enhance, ensurePrefix, ensureSuffix, escapeHTML, flattenArrayable, getObjectType, getRoot, getStringLength, getStringSimilarity, hasOwn, interopDefault, intersect, isArray, isArrayEqual, isBigInt, isBoolean, isBrowser, isDeepEqual, isElementVisibleInViewport, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isEmptyStringOrWhitespace, isError, isFunction, isHTMLElement, isInteger, isIterable, isMap, isNaN, isNativePromise, isNil, isNonEmptyArray, isNonEmptyString, isNull, isNullOrUndefined, isNumber, isNumbericString, isObject, isPromise, isRegExp, isSet, isString, isTruthy, isUndefined, isWhitespaceString, isZero, join, last, mergeArrayable, noop, omit, once, openExternalURL, pick, rAF, randomHexColor, randomNumber, randomRGBAColor, randomRGBColor, randomString, removeFileExtension, resolveSubOptions, scrollElementIntoView, slash, slugify, sortObject, throttle, toArray, toInteger, unescapeHTML, unindent, unique, uniqueBy, waitFor, warnOnce };
906
+ export { AnyFn, Arrayable, Awaitable, Callable, CleanObjectOptions, Color, CreatePadStringOptions, DeepRequired, ElementOf, GetStringSimilarityOptions, InteropModuleDefault, JsonArray, JsonObject, JsonPrimitive, JsonValue, LiteralUnion, MayBe, Merge, NOOP, NonEmptyObject, NonEmptyString, Nullable, OpenExternalURLOptions, Overwrite, Prettify, PrettifyV2, Primitive, RE_BLOCK_COMMENT, RE_COMMENTS, RE_LINE_COMMENT, RamdomNumberOptions, ResolvedOptions, SPECIAL_CHAR, STORAGE_UNITS, SortObjectOptions, StorageUnit, TIME_UNITS, ThrottleDebounceOptions, TimeUnit, ToIntegerOptions, UrlString, ValueOf, Whitespace, at, cAF, chunk, clamp, cleanObject, convertFromBytes, convertFromMilliseconds, convertStorageUnit, convertTimeUnit, convertToBytes, convertToMilliseconds, createPadString, debounce, enhance, ensurePrefix, ensureSuffix, escapeHTML, flattenArrayable, getObjectType, getRoot, getStringLength, getStringSimilarity, hasOwn, interopDefault, intersect, isArray, isArrayEqual, isBigInt, isBlob, isBoolean, isBrowser, isDeepEqual, isElementVisibleInViewport, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isEmptyStringOrWhitespace, isError, isFile, isFormData, isFunction, isHTMLElement, isInteger, isIterable, isMap, isNaN, isNativePromise, isNil, isNonEmptyArray, isNonEmptyString, isNull, isNullOrUndefined, isNumber, isNumbericString, isObject, isPromise, isRegExp, isSet, isString, isTruthy, isUndefined, isUrlString, isWhitespaceString, isZero, join, last, mergeArrayable, noop, omit, once, openExternalURL, pick, rAF, randomHexColor, randomNumber, randomRGBAColor, randomRGBColor, randomString, removeFileExtension, resolveSubOptions, scrollElementIntoView, slash, slugify, sortObject, throttle, toArray, toInteger, unescapeHTML, unindent, unique, uniqueBy, waitFor, warnOnce };
package/dist/index.js CHANGED
@@ -10,6 +10,22 @@ const NOOP = noop;
10
10
 
11
11
  //#endregion
12
12
  //#region src/fn/once.ts
13
+ /**
14
+ * Creates a function that is restricted to invoking `func` once. Repeat calls to the function return `false`.
15
+ *
16
+ * @param func - The function to restrict.
17
+ * @returns A new function that returns `true` when `func` is invoked for the first time and `false` on subsequent calls.
18
+ *
19
+ * @example
20
+ *
21
+ * ```ts
22
+ * const initialize = once(() => {
23
+ * console.log('Initialized')
24
+ * })
25
+ *
26
+ * initialize() // Logs: 'Initialized', returns true
27
+ * ```
28
+ */
13
29
  function once(func) {
14
30
  let called = false;
15
31
  return function(...args) {
@@ -139,6 +155,24 @@ function isPromise(value) {
139
155
  function isIterable(value) {
140
156
  return isFunction(value?.[Symbol.iterator]);
141
157
  }
158
+ function isBlob(value) {
159
+ return getObjectType(value) === "Blob";
160
+ }
161
+ function isFormData(value) {
162
+ return getObjectType(value) === "FormData";
163
+ }
164
+ function isFile(value) {
165
+ return getObjectType(value) === "File";
166
+ }
167
+ function isUrlString(value) {
168
+ if (!isString(value)) return false;
169
+ try {
170
+ new URL(value);
171
+ return true;
172
+ } catch {
173
+ return false;
174
+ }
175
+ }
142
176
 
143
177
  //#endregion
144
178
  //#region src/is/isDeepEqual.ts
@@ -146,9 +180,7 @@ function isIterable(value) {
146
180
  * check if two values are deeply equal
147
181
  */
148
182
  function isDeepEqual(value1, value2) {
149
- const type1 = getObjectType(value1);
150
- const type2 = getObjectType(value2);
151
- if (type1 !== type2) return false;
183
+ if (getObjectType(value1) !== getObjectType(value2)) return false;
152
184
  if (isArray(value1) && isArray(value2)) {
153
185
  if (value1.length !== value2.length) return false;
154
186
  return value1.every((item, index) => isDeepEqual(item, value2[index]));
@@ -171,16 +203,14 @@ function isDeepEqual(value1, value2) {
171
203
  */
172
204
  function scrollElementIntoView(element, options = {}) {
173
205
  const body = document.body;
174
- const { parent = body,...scrollIntoViewOptions } = options;
206
+ const { parent = body, ...scrollIntoViewOptions } = options;
175
207
  if (parent === body) {
176
208
  parent.scrollIntoView(scrollIntoViewOptions);
177
209
  return;
178
210
  }
179
211
  const parentRect = parent.getBoundingClientRect();
180
212
  const elementRect = element.getBoundingClientRect();
181
- const isHorizontal = parent.scrollWidth > parent.scrollHeight;
182
- const isOutOfView = isHorizontal ? elementRect.left < parentRect.left || elementRect.right > parentRect.right : elementRect.top < parentRect.top || elementRect.bottom > parentRect.bottom;
183
- if (isOutOfView) parent.scrollIntoView(scrollIntoViewOptions);
213
+ if (parent.scrollWidth > parent.scrollHeight ? elementRect.left < parentRect.left || elementRect.right > parentRect.right : elementRect.top < parentRect.top || elementRect.bottom > parentRect.bottom) parent.scrollIntoView(scrollIntoViewOptions);
184
214
  }
185
215
 
186
216
  //#endregion
@@ -193,8 +223,7 @@ function scrollElementIntoView(element, options = {}) {
193
223
  */
194
224
  function openExternalURL(url, options = {}) {
195
225
  const { target = "_blank" } = options;
196
- const proxy = window.open(url, target);
197
- return proxy;
226
+ return window.open(url, target);
198
227
  }
199
228
 
200
229
  //#endregion
@@ -276,6 +305,9 @@ function unescapeHTML(str) {
276
305
  //#endregion
277
306
  //#region src/misc/raf.ts
278
307
  /**
308
+ * @file raf.ts
309
+ */
310
+ /**
279
311
  * Gets the global root object.
280
312
  * @returns the global root object
281
313
  */
@@ -290,8 +322,7 @@ function getRoot() {
290
322
  */
291
323
  function rAF(fn) {
292
324
  const root = getRoot();
293
- const raf = root.requestAnimationFrame;
294
- return raf.call(root, fn);
325
+ return root.requestAnimationFrame.call(root, fn);
295
326
  }
296
327
  /**
297
328
  * Cancel animation frame
@@ -301,8 +332,7 @@ function rAF(fn) {
301
332
  */
302
333
  function cAF(id) {
303
334
  const root = getRoot();
304
- const caf = root.cancelAnimationFrame;
305
- return caf.call(root, id);
335
+ return root.cancelAnimationFrame.call(root, id);
306
336
  }
307
337
 
308
338
  //#endregion
@@ -467,8 +497,7 @@ function convertFromMilliseconds(milliseconds, toUnit = "SECOND") {
467
497
  * ```
468
498
  */
469
499
  function convertTimeUnit(value, fromUnit, toUnit) {
470
- const milliseconds = convertToMilliseconds(value, fromUnit);
471
- return convertFromMilliseconds(milliseconds, toUnit);
500
+ return convertFromMilliseconds(convertToMilliseconds(value, fromUnit), toUnit);
472
501
  }
473
502
 
474
503
  //#endregion
@@ -531,8 +560,7 @@ function convertFromBytes(bytes, toUnit = "MB") {
531
560
  * ```
532
561
  */
533
562
  function convertStorageUnit(value, fromUnit, toUnit) {
534
- const bytes = convertToBytes(value, fromUnit);
535
- return convertFromBytes(bytes, toUnit);
563
+ return convertFromBytes(convertToBytes(value, fromUnit), toUnit);
536
564
  }
537
565
 
538
566
  //#endregion
@@ -545,7 +573,7 @@ function convertStorageUnit(value, fromUnit, toUnit) {
545
573
  */
546
574
  function at(array, index) {
547
575
  const length = array.length;
548
- if (!length) return void 0;
576
+ if (!length) return;
549
577
  if (index < 0) index += length;
550
578
  return array[index];
551
579
  }
@@ -590,8 +618,7 @@ function unique(array) {
590
618
  */
591
619
  function uniqueBy(array, equalFn) {
592
620
  return array.reduce((acc, cur) => {
593
- const idx = acc.findIndex((item) => equalFn(item, cur));
594
- if (idx === -1) acc.push(cur);
621
+ if (acc.findIndex((item) => equalFn(item, cur)) === -1) acc.push(cur);
595
622
  return acc;
596
623
  }, []);
597
624
  }
@@ -759,7 +786,10 @@ function toInteger(value, options = {}) {
759
786
  */
760
787
  function randomString(length = 16, chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
761
788
  const result = [];
762
- for (let i = length; i > 0; --i) result.push(chars[randomNumber(chars.length)]);
789
+ for (let i = length; i > 0; --i) {
790
+ const matchedChar = chars[randomNumber(chars.length)];
791
+ if (matchedChar) result.push(matchedChar);
792
+ }
763
793
  return result.join("");
764
794
  }
765
795
 
@@ -794,7 +824,7 @@ const _RE_FULL_WS = /^\s*$/;
794
824
  * ```
795
825
  */
796
826
  function unindent(input) {
797
- const lines = (typeof input === "string" ? input : input[0]).split("\n");
827
+ const lines = (isString(input) ? input : input[0])?.split("\n") ?? [];
798
828
  const whitespaceLines = lines.map((line) => _RE_FULL_WS.test(line));
799
829
  const commonIndent = lines.reduce((min, line, idx) => {
800
830
  if (whitespaceLines[idx]) return min;
@@ -1072,9 +1102,10 @@ function hasOwn(object, key) {
1072
1102
  //#endregion
1073
1103
  //#region src/object/pick.ts
1074
1104
  function pick(object, keys) {
1075
- return Object.assign({}, ...keys.map((key) => {
1076
- if (object && hasOwn(object, key)) return { [key]: object[key] };
1077
- }));
1105
+ return keys.reduce((result, key) => {
1106
+ if (object && hasOwn(object, key)) result[key] = object[key];
1107
+ return result;
1108
+ }, {});
1078
1109
  }
1079
1110
 
1080
1111
  //#endregion
@@ -1145,7 +1176,14 @@ function sortObject(obj, options = {}) {
1145
1176
  /**
1146
1177
  * Special chars
1147
1178
  */
1148
- const SPECIAL_CHAR = { newline: "\n" };
1179
+ const SPECIAL_CHAR = {
1180
+ chineseComma: "、",
1181
+ englishComma: ",",
1182
+ englishPeriod: ".",
1183
+ hyphen: "-",
1184
+ newline: "\n",
1185
+ whitespace: " "
1186
+ };
1149
1187
 
1150
1188
  //#endregion
1151
1189
  //#region src/constants/regexp.ts
@@ -1165,4 +1203,4 @@ const RE_LINE_COMMENT = /\/\/.*/;
1165
1203
  const RE_BLOCK_COMMENT = /\/\*[\s\S]*?\*\//g;
1166
1204
 
1167
1205
  //#endregion
1168
- export { Color, NOOP, RE_BLOCK_COMMENT, RE_COMMENTS, RE_LINE_COMMENT, SPECIAL_CHAR, STORAGE_UNITS, TIME_UNITS, at, cAF, chunk, clamp, cleanObject, convertFromBytes, convertFromMilliseconds, convertStorageUnit, convertTimeUnit, convertToBytes, convertToMilliseconds, createPadString, debounce, enhance, ensurePrefix, ensureSuffix, escapeHTML, flattenArrayable, getObjectType, getRoot, getStringLength, getStringSimilarity, hasOwn, interopDefault, intersect, isArray, isArrayEqual, isBigInt, isBoolean, isBrowser, isDeepEqual, isElementVisibleInViewport, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isEmptyStringOrWhitespace, isError, isFunction, isHTMLElement, isInteger, isIterable, isMap, isNaN, isNativePromise, isNil, isNonEmptyArray, isNonEmptyString, isNull, isNullOrUndefined, isNumber, isNumbericString, isObject, isPromise, isRegExp, isSet, isString, isTruthy, isUndefined, isWhitespaceString, isZero, join, last, mergeArrayable, noop, omit, once, openExternalURL, pick, rAF, randomHexColor, randomNumber, randomRGBAColor, randomRGBColor, randomString, removeFileExtension, resolveSubOptions, scrollElementIntoView, slash, slugify, sortObject, throttle, toArray, toInteger, unescapeHTML, unindent, unique, uniqueBy, waitFor, warnOnce };
1206
+ export { Color, NOOP, RE_BLOCK_COMMENT, RE_COMMENTS, RE_LINE_COMMENT, SPECIAL_CHAR, STORAGE_UNITS, TIME_UNITS, at, cAF, chunk, clamp, cleanObject, convertFromBytes, convertFromMilliseconds, convertStorageUnit, convertTimeUnit, convertToBytes, convertToMilliseconds, createPadString, debounce, enhance, ensurePrefix, ensureSuffix, escapeHTML, flattenArrayable, getObjectType, getRoot, getStringLength, getStringSimilarity, hasOwn, interopDefault, intersect, isArray, isArrayEqual, isBigInt, isBlob, isBoolean, isBrowser, isDeepEqual, isElementVisibleInViewport, isEmptyArray, isEmptyMap, isEmptyObject, isEmptySet, isEmptyString, isEmptyStringOrWhitespace, isError, isFile, isFormData, isFunction, isHTMLElement, isInteger, isIterable, isMap, isNaN, isNativePromise, isNil, isNonEmptyArray, isNonEmptyString, isNull, isNullOrUndefined, isNumber, isNumbericString, isObject, isPromise, isRegExp, isSet, isString, isTruthy, isUndefined, isUrlString, isWhitespaceString, isZero, join, last, mergeArrayable, noop, omit, once, openExternalURL, pick, rAF, randomHexColor, randomNumber, randomRGBAColor, randomRGBColor, randomString, removeFileExtension, resolveSubOptions, scrollElementIntoView, slash, slugify, sortObject, throttle, toArray, toInteger, unescapeHTML, unindent, unique, uniqueBy, waitFor, warnOnce };
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@ntnyq/utils",
3
3
  "type": "module",
4
- "version": "0.9.1",
5
- "packageManager": "pnpm@10.14.0",
4
+ "version": "0.10.0",
5
+ "packageManager": "pnpm@10.26.2",
6
6
  "description": "Common used utils.",
7
7
  "keywords": [
8
8
  "utils"
@@ -43,20 +43,21 @@
43
43
  "typecheck": "tsc --noEmit"
44
44
  },
45
45
  "devDependencies": {
46
- "@ntnyq/eslint-config": "^5.3.1",
46
+ "@ntnyq/eslint-config": "^5.8.0",
47
47
  "@ntnyq/prettier-config": "^3.0.1",
48
- "bumpp": "^10.2.3",
49
- "eslint": "^9.33.0",
48
+ "@ntnyq/tsconfig": "^3.0.0",
49
+ "bumpp": "^10.3.2",
50
+ "eslint": "^9.39.2",
50
51
  "husky": "^9.1.7",
51
- "nano-staged": "^0.8.0",
52
+ "nano-staged": "^0.9.0",
52
53
  "npm-run-all2": "^8.0.4",
53
- "prettier": "^3.6.2",
54
- "tsdown": "^0.14.1",
55
- "typescript": "^5.9.2",
56
- "vitest": "^3.2.4"
54
+ "prettier": "^3.7.4",
55
+ "tsdown": "^0.18.3",
56
+ "typescript": "^5.9.3",
57
+ "vitest": "^4.0.15"
57
58
  },
58
59
  "engines": {
59
- "node": ">=18.18.0"
60
+ "node": "^20.19.0 || ^22.13.0 || >=24"
60
61
  },
61
62
  "nano-staged": {
62
63
  "*.{js,ts,mjs,cjs,md,yml,yaml,toml,json}": "eslint --fix"