devcraft-js 0.0.0-stage → 0.1.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/README.md CHANGED
@@ -1,3 +1,1462 @@
1
- # Temporary Holding Version
1
+ # DevCraft JS
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A modular JavaScript utility toolkit for developers.
4
+
5
+ DevCraft JS provides reusable helpers for common array, object, string, asynchronous, function-composition, and validation tasks. It is distributed as an npm package with both ES module (ESM) and CommonJS entry points.
6
+
7
+ > **Release status:** The package is being prepared for its first npm release. The examples below document the implementation in this repository. TypeScript declaration files are not included in the initial release.
8
+
9
+ ## Contents
10
+
11
+ - [Features](#features)
12
+ - [Installation](#installation)
13
+ - [Requirements](#requirements)
14
+ - [Quick start](#quick-start)
15
+ - [Module overview](#module-overview)
16
+ - [API reference](#api-reference)
17
+ - [Array utilities](#1-array-utilities)
18
+ - [Object utilities](#2-object-utilities)
19
+ - [String utilities](#3-string-utilities)
20
+ - [Async utilities](#4-async-utilities)
21
+ - [Function utilities](#5-function-utilities)
22
+ - [Validation utilities](#6-validation-utilities)
23
+ - [Error handling and behavior notes](#error-handling-and-behavior-notes)
24
+ - [Module formats](#module-formats)
25
+ - [Project structure](#project-structure)
26
+ - [Development](#development)
27
+ - [Testing](#testing)
28
+ - [Contributing](#contributing)
29
+ - [License](#license)
30
+
31
+ ## Features
32
+
33
+ - 48 utility functions across six focused modules.
34
+ - ESM and CommonJS builds.
35
+ - Tree-friendly named exports from the package root.
36
+ - No declared runtime dependencies.
37
+ - Input validation for many utility functions.
38
+ - Automated tests using Vitest.
39
+ - Build output generated with tsup.
40
+
41
+ ## Installation
42
+
43
+ After `devcraft-js` is published to npm, install it with:
44
+
45
+ ```bash
46
+ npm install devcraft-js
47
+ ```
48
+
49
+ For the current local repository, build the package first:
50
+
51
+ ```bash
52
+ npm install
53
+ npm run build
54
+ ```
55
+
56
+ Then you can test it from a separate project by installing the generated `.tgz` archive (see [Testing a packed installation](#testing-a-packed-installation)).
57
+
58
+ ## Requirements
59
+
60
+ - Node.js **18 or newer**, as declared in `package.json`.
61
+ - npm or another compatible package manager.
62
+
63
+ The package provides JavaScript ESM and CommonJS entry points. TypeScript declaration files are not currently included, so this release should not be described as having first-party TypeScript type declarations.
64
+
65
+ ## Quick start
66
+
67
+ ### ES modules
68
+
69
+ ```js
70
+ import {
71
+ chunk,
72
+ unique,
73
+ deepClone,
74
+ camelCase,
75
+ retry,
76
+ isEmail,
77
+ } from "devcraft-js";
78
+
79
+ console.log(chunk([1, 2, 3, 4, 5], 2));
80
+ // [[1, 2], [3, 4], [5]]
81
+
82
+ console.log(unique([1, 2, 2, 3]));
83
+ // [1, 2, 3]
84
+
85
+ console.log(deepClone({ user: { name: "Utkarsh" } }));
86
+ // { user: { name: "Utkarsh" } }
87
+
88
+ console.log(camelCase("hello_world"));
89
+ // "helloWorld"
90
+
91
+ const result = await retry(
92
+ async () => {
93
+ // Replace with an operation that may fail temporarily.
94
+ return "Request completed";
95
+ },
96
+ { retries: 2, delay: 250 },
97
+ );
98
+
99
+ console.log(result);
100
+ // "Request completed"
101
+
102
+ console.log(isEmail("developer@example.com"));
103
+ // true
104
+ ```
105
+
106
+ ### CommonJS
107
+
108
+ ```js
109
+ const {
110
+ chunk,
111
+ groupBy,
112
+ sleep,
113
+ isURL,
114
+ } = require("devcraft-js");
115
+
116
+ console.log(chunk([1, 2, 3, 4], 2));
117
+ // [[1, 2], [3, 4]]
118
+
119
+ console.log(
120
+ groupBy(
121
+ [
122
+ { name: "A", role: "admin" },
123
+ { name: "B", role: "user" },
124
+ { name: "C", role: "admin" },
125
+ ],
126
+ "role",
127
+ ),
128
+ );
129
+ // {
130
+ // admin: [{ name: "A", role: "admin" }, { name: "C", role: "admin" }],
131
+ // user: [{ name: "B", role: "user" }]
132
+ // }
133
+
134
+ sleep(100).then(() => {
135
+ console.log(isURL("https://example.com"));
136
+ // true
137
+ });
138
+ ```
139
+
140
+ ## Module overview
141
+
142
+ | Module | Functions | Purpose |
143
+ | --- | ---: | --- |
144
+ | Array | 8 | Transform, group, filter, flatten, and compare arrays |
145
+ | Object | 9 | Clone, merge, select, access, mutate, and sort object data |
146
+ | String | 8 | Change string casing, truncate, reverse, count, and inspect text |
147
+ | Async | 7 | Work with delays, retries, timeouts, concurrency, and promises |
148
+ | Function | 7 | Build reusable functions through caching, currying, composition, and debouncing |
149
+ | Validation | 9 | Check common string, number, URL, JSON, password, and emptiness rules |
150
+ | **Total** | **48** | |
151
+
152
+ # API reference
153
+
154
+ All functions are available as named exports from the package root:
155
+
156
+ ```js
157
+ import { chunk, deepClone, isEmail } from "devcraft-js";
158
+ ```
159
+
160
+ The examples use ESM syntax. The same named exports are available through `require("devcraft-js")` in CommonJS projects.
161
+
162
+ ## 1. Array utilities
163
+
164
+ Import from the package root:
165
+
166
+ ```js
167
+ import {
168
+ chunk,
169
+ unique,
170
+ uniqueBy,
171
+ groupBy,
172
+ partition,
173
+ shuffle,
174
+ flatten,
175
+ difference,
176
+ } from "devcraft-js";
177
+ ```
178
+
179
+ ### `chunk(array, size)`
180
+
181
+ Splits an array into consecutive smaller arrays containing at most `size` elements each. The final chunk may contain fewer elements. The input array is not mutated.
182
+
183
+ ```js
184
+ chunk([1, 2, 3, 4, 5], 2);
185
+ // [[1, 2], [3, 4], [5]]
186
+ ```
187
+
188
+ - `array` (`Array`): Input array.
189
+ - `size` (`number`): Positive integer maximum size of each chunk.
190
+ - Returns: A new array containing shallow copies of the chunks.
191
+ - Throws: `TypeError` if the input is not an array; `RangeError` if `size` is not a positive integer.
192
+
193
+ ### `unique(array)`
194
+
195
+ Removes duplicate values while preserving the order of their first occurrence. It uses JavaScript `Set` equality (SameValueZero); objects are considered equal only when they are the same reference.
196
+
197
+ ```js
198
+ unique([1, 2, 2, 3, 1, NaN, NaN]);
199
+ // [1, 2, 3, NaN]
200
+ ```
201
+
202
+ - `array` (`Array`): Input array.
203
+ - Returns: A new array containing unique values.
204
+ - Throws: `TypeError` if the input is not an array.
205
+
206
+ ### `uniqueBy(array, keyOrFn)`
207
+
208
+ Removes duplicate elements according to a property name or a callback. The first element for each computed key is retained.
209
+
210
+ ```js
211
+ const users = [
212
+ { id: 1, name: "Asha" },
213
+ { id: 2, name: "Ravi" },
214
+ { id: 1, name: "Asha duplicate" },
215
+ ];
216
+
217
+ uniqueBy(users, "id");
218
+ // [{ id: 1, name: "Asha" }, { id: 2, name: "Ravi" }]
219
+
220
+ uniqueBy(users, (user) => user.name.length);
221
+ // Keeps the first user for each distinct name length.
222
+ ```
223
+
224
+ - `array` (`Array`): Input array.
225
+ - `keyOrFn` (`string | Function`): Property name or callback called with `(item, index)`.
226
+ - Returns: A new array containing the first element for each unique key.
227
+ - Throws: `TypeError` if the input is not an array or `keyOrFn` is neither a string nor a function.
228
+
229
+ ### `groupBy(array, keyOrFn)`
230
+
231
+ Groups elements into an object using a property name or callback result as the group key. Each key is converted to a string. Group order follows the first occurrence of each key.
232
+
233
+ ```js
234
+ const products = [
235
+ { name: "Mouse", category: "Accessories" },
236
+ { name: "Keyboard", category: "Accessories" },
237
+ { name: "Monitor", category: "Displays" },
238
+ ];
239
+
240
+ groupBy(products, "category");
241
+ // {
242
+ // Accessories: [
243
+ // { name: "Mouse", category: "Accessories" },
244
+ // { name: "Keyboard", category: "Accessories" }
245
+ // ],
246
+ // Displays: [{ name: "Monitor", category: "Displays" }]
247
+ // }
248
+
249
+ groupBy(products, (product) => product.name.length);
250
+ ```
251
+
252
+ - `array` (`Array`): Input array.
253
+ - `keyOrFn` (`string | Function`): Property name or callback called with `(item, index)`.
254
+ - Returns: An object whose properties contain arrays of grouped elements. Callback results are converted with `String(key)`.
255
+ - Throws: `TypeError` if the input is not an array or `keyOrFn` is neither a string nor a function.
256
+
257
+ ### `partition(array, predicate)`
258
+
259
+ Splits an array into two arrays: elements for which the predicate returns a truthy value, followed by elements for which it returns a falsy value.
260
+
261
+ ```js
262
+ const [adults, minors] = partition(
263
+ [12, 18, 25, 16, 32],
264
+ (age) => age >= 18,
265
+ );
266
+
267
+ console.log(adults); // [18, 25, 32]
268
+ console.log(minors); // [12, 16]
269
+ ```
270
+
271
+ - `array` (`Array`): Input array.
272
+ - `predicate` (`Function`): Called with `(value, index)` for each present array element.
273
+ - Returns: A two-element array `[matched, unmatched]`.
274
+ - Notes: Sparse array holes are skipped, like `Array.prototype.forEach`.
275
+ - Throws: `TypeError` if the input is not an array or the predicate is not a function.
276
+
277
+ ### `shuffle(array)`
278
+
279
+ Returns a shuffled shallow copy using the Fisher–Yates algorithm. The original array is not mutated.
280
+
281
+ ```js
282
+ const values = [1, 2, 3, 4, 5];
283
+ const shuffled = shuffle(values);
284
+
285
+ console.log(shuffled); // A shuffled ordering
286
+ console.log(values); // [1, 2, 3, 4, 5]
287
+ ```
288
+
289
+ - `array` (`Array`): Input array.
290
+ - Returns: A new array in randomized order.
291
+ - Notes: Uses `Math.random()`; it is not intended for cryptographic or security-sensitive randomness.
292
+ - Throws: `TypeError` if the input is not an array.
293
+
294
+ ### `flatten(array, depth = 1)`
295
+
296
+ Flattens nested arrays up to the specified depth. The default depth is `1`, matching the default behavior of `Array.prototype.flat`.
297
+
298
+ ```js
299
+ flatten([1, [2, [3, [4]]]]);
300
+ // [1, 2, [3, [4]]]
301
+
302
+ flatten([1, [2, [3, [4]]]], 2);
303
+ // [1, 2, 3, [4]]
304
+
305
+ flatten([1, [2, [3]]], Infinity);
306
+ // [1, 2, 3]
307
+ ```
308
+
309
+ - `array` (`Array`): Input array.
310
+ - `depth` (`number`, optional): Non-negative integer or `Infinity`; defaults to `1`.
311
+ - Returns: A new flattened array.
312
+ - Notes: Sparse slots are skipped, following `Array.prototype.flat`.
313
+ - Throws: `TypeError` if the input is not an array; `RangeError` for an invalid depth.
314
+
315
+ ### `difference(array, other)`
316
+
317
+ Returns the values from the first array that are not present in the second array. Membership uses `Set`/SameValueZero semantics. The order and duplicates from the first array are preserved when a value is not excluded.
318
+
319
+ ```js
320
+ difference([1, 2, 2, 3, 4], [2, 4]);
321
+ // [1, 3]
322
+
323
+ difference(["a", "b", "c"], ["b"]);
324
+ // ["a", "c"]
325
+ ```
326
+
327
+ - `array` (`Array`): Array whose values are filtered.
328
+ - `other` (`Array`): Values to exclude.
329
+ - Returns: A new array; neither input is mutated.
330
+ - Throws: `TypeError` if either argument is not an array.
331
+
332
+ ## 2. Object utilities
333
+
334
+ Import from the package root:
335
+
336
+ ```js
337
+ import {
338
+ deepClone,
339
+ deepMerge,
340
+ pick,
341
+ omit,
342
+ get,
343
+ set,
344
+ has,
345
+ sortByKey,
346
+ sortByMultiple,
347
+ } from "devcraft-js";
348
+ ```
349
+
350
+ ### `deepClone(value)`
351
+
352
+ Creates a deep clone of supported values. It preserves circular references and shared references between properties. It also supports common built-in data structures such as `Date`, `RegExp`, `Map`, `Set`, `ArrayBuffer`, typed-array views, and `DataView`.
353
+
354
+ ```js
355
+ const original = {
356
+ user: { name: "Asha" },
357
+ createdAt: new Date("2025-01-01"),
358
+ };
359
+
360
+ const copy = deepClone(original);
361
+
362
+ copy.user.name = "Ravi";
363
+
364
+ console.log(original.user.name); // "Asha"
365
+ console.log(copy.user.name); // "Ravi"
366
+ ```
367
+
368
+ Circular and shared references are preserved:
369
+
370
+ ```js
371
+ const shared = { enabled: true };
372
+ const original = { first: shared, second: shared };
373
+ original.self = original;
374
+
375
+ const copy = deepClone(original);
376
+
377
+ console.log(copy.first === copy.second); // true
378
+ console.log(copy.self === copy); // true
379
+ ```
380
+
381
+ - `value` (`any`): Value to clone.
382
+ - Returns: A cloned value.
383
+ - Notes:
384
+ - Functions and primitive values are returned unchanged; functions are retained by reference.
385
+ - Property descriptors and symbol keys are preserved by the implementation's object-cloning path.
386
+ - `Promise`, `WeakMap`, `WeakSet`, `SharedArrayBuffer`, and host objects with unsupported internal slots are not supported and may throw.
387
+ - The optional internal `seen` parameter is used for tracking already-cloned references; normal callers should omit it.
388
+ - Throws: `TypeError` for explicitly unsupported values.
389
+
390
+ ### `deepMerge(target, ...sources)`
391
+
392
+ Deeply merges one or more source objects into a cloned target. Nested plain objects are merged recursively. Arrays and non-plain/special values replace the corresponding target value and are cloned. The original target and sources are not mutated.
393
+
394
+ ```js
395
+ const target = {
396
+ user: {
397
+ name: "Asha",
398
+ preferences: { theme: "light" },
399
+ },
400
+ tags: ["javascript"],
401
+ };
402
+
403
+ const source = {
404
+ user: {
405
+ preferences: { language: "en" },
406
+ },
407
+ tags: ["nodejs"],
408
+ };
409
+
410
+ const result = deepMerge(target, source);
411
+
412
+ console.log(result);
413
+ // {
414
+ // user: {
415
+ // name: "Asha",
416
+ // preferences: { theme: "light", language: "en" }
417
+ // },
418
+ // tags: ["nodejs"]
419
+ // }
420
+ ```
421
+
422
+ - `target` (`Object`): Initial plain object.
423
+ - `sources` (`...Object[]`): One or more source plain objects.
424
+ - Returns: A new merged object.
425
+ - Notes:
426
+ - Only plain objects (objects with `Object.prototype` or `null` prototype) are accepted as target and sources.
427
+ - Arrays and special values are replaced rather than recursively merged.
428
+ - Unsafe property names `__proto__`, `constructor`, and `prototype` are skipped during source merging.
429
+ - Cyclic source objects are rejected.
430
+ - Throws: `TypeError` if target or any source is not a plain object, or if a source contains a cycle.
431
+
432
+ ### `pick(object, keys)`
433
+
434
+ Creates a new object containing only the requested own properties that exist on the input object.
435
+
436
+ ```js
437
+ const user = {
438
+ id: 7,
439
+ name: "Asha",
440
+ password: "hidden",
441
+ };
442
+
443
+ pick(user, ["id", "name"]);
444
+ // { id: 7, name: "Asha" }
445
+ ```
446
+
447
+ - `object` (`Object`): Source object.
448
+ - `keys` (`Array`): Property keys to include.
449
+ - Returns: A new object containing the selected own properties.
450
+ - Notes: The function checks own properties, not inherited properties. Values are copied by reference; this is not a deep clone.
451
+ - Throws: `TypeError` if the input is null/non-object or `keys` is not an array.
452
+
453
+ ### `omit(object, keys)`
454
+
455
+ Creates a new object containing the input object's own enumerable string-keyed properties except those listed in `keys`.
456
+
457
+ ```js
458
+ const user = {
459
+ id: 7,
460
+ name: "Asha",
461
+ password: "hidden",
462
+ };
463
+
464
+ omit(user, ["password"]);
465
+ // { id: 7, name: "Asha" }
466
+ ```
467
+
468
+ - `object` (`Object`): Source object.
469
+ - `keys` (`Array`): Property keys to exclude.
470
+ - Returns: A new object without the excluded properties.
471
+ - Notes: This implementation iterates `Object.keys()`, so it copies own enumerable string-keyed properties. It is a shallow operation.
472
+ - Throws: `TypeError` if the input is null/non-object or `keys` is not an array.
473
+
474
+ ### `get(object, path, fallback)`
475
+
476
+ Reads a nested own property using a dot-separated string path or an array of path segments. Returns `fallback` if any path segment is missing. If the property exists with the value `undefined`, it returns `undefined` rather than the fallback.
477
+
478
+ ```js
479
+ const user = {
480
+ profile: {
481
+ address: {
482
+ city: "Ujjain",
483
+ },
484
+ },
485
+ };
486
+
487
+ get(user, "profile.address.city");
488
+ // "Ujjain"
489
+
490
+ get(user, "profile.address.country", "India");
491
+ // "India"
492
+
493
+ get(user, ["profile", "address", "city"]);
494
+ // "Ujjain"
495
+ ```
496
+
497
+ - `object` (`Object`): Value from which to read.
498
+ - `path` (`string | Array`): Dot-separated path or array of segments.
499
+ - `fallback` (`any`, optional): Value returned when a segment is absent.
500
+ - Returns: The resolved property value or fallback.
501
+ - Notes: Only own properties are traversed. Empty path segments and the unsafe segments `__proto__`, `constructor`, and `prototype` are rejected.
502
+ - Throws: `TypeError` for an invalid path.
503
+
504
+ ### `set(root, path, value)`
505
+
506
+ Sets a nested own property and mutates the supplied root object. Missing intermediate objects are created automatically. If the next path segment is numeric, an array is created for that level.
507
+
508
+ ```js
509
+ const user = {};
510
+
511
+ set(user, "profile.name", "Asha");
512
+ set(user, "profile.skills.0", "JavaScript");
513
+
514
+ console.log(user);
515
+ // {
516
+ // profile: {
517
+ // name: "Asha",
518
+ // skills: ["JavaScript"]
519
+ // }
520
+ // }
521
+ ```
522
+
523
+ - `root` (`Object`): Root object to modify.
524
+ - `path` (`string | Array`): Dot-separated path or array of segments.
525
+ - `value` (`any`): Value to assign.
526
+ - Returns: The same root object after mutation.
527
+ - Notes: Unsafe path segments `__proto__`, `constructor`, and `prototype` are rejected.
528
+ - Throws: `TypeError` if root is null/non-object or path is invalid.
529
+
530
+ ### `has(object, path)`
531
+
532
+ Checks whether a nested own property exists. It returns `true` even if the final property's value is `undefined`.
533
+
534
+ ```js
535
+ const settings = {
536
+ user: {
537
+ nickname: undefined,
538
+ },
539
+ };
540
+
541
+ has(settings, "user.nickname"); // true
542
+ has(settings, "user.email"); // false
543
+ ```
544
+
545
+ - `object` (`Object`): Object to inspect.
546
+ - `path` (`string | Array`): Dot-separated path or array of segments.
547
+ - Returns: Boolean indicating whether every path segment exists as an own property.
548
+ - Notes: Inherited properties do not count. Unsafe path segments are rejected.
549
+ - Throws: `TypeError` for an invalid path.
550
+
551
+ ### `sortByKey(array, key, order = "asc")`
552
+
553
+ Returns a stable sorted copy of an array of objects using one property as the sorting key. The original array is not mutated.
554
+
555
+ ```js
556
+ const users = [
557
+ { name: "Ravi", age: 25 },
558
+ { name: "Asha", age: 20 },
559
+ { name: "Kabir", age: 23 },
560
+ ];
561
+
562
+ sortByKey(users, "age");
563
+ // Asha (20), Kabir (23), Ravi (25)
564
+
565
+ sortByKey(users, "age", "desc");
566
+ // Ravi (25), Kabir (23), Asha (20)
567
+ ```
568
+
569
+ - `array` (`Array`): Input array.
570
+ - `key` (`string`): Property name used for comparison.
571
+ - `order` (`"asc" | "desc"`, optional): Sort direction; defaults to `"asc"`.
572
+ - Returns: A new stable-sorted array.
573
+ - Notes:
574
+ - Missing and nullish values sort last in both directions.
575
+ - String values are compared with `localeCompare` using base sensitivity.
576
+ - Other values use JavaScript relational comparison.
577
+ - Throws: `TypeError` if `array` is not an array or `key` is not a string; `RangeError` for an invalid order.
578
+
579
+ ### `sortByMultiple(array, criteria)`
580
+
581
+ Returns a stable sorted copy using multiple sorting rules in priority order. Each criterion must contain a `key` and an `order`.
582
+
583
+ ```js
584
+ const employees = [
585
+ { name: "Asha", department: "Engineering", salary: 70000 },
586
+ { name: "Ravi", department: "Engineering", salary: 80000 },
587
+ { name: "Kabir", department: "Design", salary: 75000 },
588
+ ];
589
+
590
+ sortByMultiple(employees, [
591
+ { key: "department", order: "asc" },
592
+ { key: "salary", order: "desc" },
593
+ ]);
594
+ // First by department ascending, then salary descending.
595
+ ```
596
+
597
+ - `array` (`Array`): Input array.
598
+ - `criteria` (`Array<{ key: string, order: "asc" | "desc" }>`): Ordered sorting criteria.
599
+ - Returns: A new stable-sorted array.
600
+ - Notes: Missing and nullish values sort last for each criterion. If all criteria compare equal, original order is retained.
601
+ - Throws: `TypeError` if the array or criteria structure is invalid.
602
+
603
+ ## 3. String utilities
604
+
605
+ Import from the package root:
606
+
607
+ ```js
608
+ import {
609
+ capitalize,
610
+ camelCase,
611
+ kebabCase,
612
+ snakeCase,
613
+ truncate,
614
+ reverse,
615
+ countWords,
616
+ isPalindrome,
617
+ } from "devcraft-js";
618
+ ```
619
+
620
+ ### `capitalize(str)`
621
+
622
+ Converts the first Unicode code point to uppercase and leaves the rest of the string unchanged.
623
+
624
+ ```js
625
+ capitalize("hello world"); // "Hello world"
626
+ capitalize("javascript"); // "Javascript"
627
+ capitalize(""); // ""
628
+ ```
629
+
630
+ - `str` (`string`): Input string.
631
+ - Returns: Capitalized string.
632
+ - Throws: `TypeError` if the input is not a string.
633
+
634
+ ### `camelCase(str)`
635
+
636
+ Converts separated words to camelCase. It recognizes whitespace, hyphens, underscores, and common lower-to-upper or acronym-to-word boundaries.
637
+
638
+ ```js
639
+ camelCase("hello world"); // "helloWorld"
640
+ camelCase("hello_world"); // "helloWorld"
641
+ camelCase("background-color"); // "backgroundColor"
642
+ camelCase("XMLHttpRequest"); // "xmlHttpRequest"
643
+ ```
644
+
645
+ - `str` (`string`): Input string.
646
+ - Returns: camelCase string.
647
+ - Notes: Punctuation within words is retained.
648
+ - Throws: `TypeError` if the input is not a string.
649
+
650
+ ### `kebabCase(str)`
651
+
652
+ Converts separated words to lowercase kebab-case, using hyphens between words.
653
+
654
+ ```js
655
+ kebabCase("Hello World"); // "hello-world"
656
+ kebabCase("backgroundColor"); // "background-color"
657
+ kebabCase("user_profile_name"); // "user-profile-name"
658
+ ```
659
+
660
+ - `str` (`string`): Input string.
661
+ - Returns: kebab-case string.
662
+ - Notes: Punctuation within words is retained.
663
+ - Throws: `TypeError` if the input is not a string.
664
+
665
+ ### `snakeCase(str)`
666
+
667
+ Converts separated words to lowercase snake_case, using underscores between words.
668
+
669
+ ```js
670
+ snakeCase("Hello World"); // "hello_world"
671
+ snakeCase("backgroundColor"); // "background_color"
672
+ snakeCase("user-profile-name"); // "user_profile_name"
673
+ ```
674
+
675
+ - `str` (`string`): Input string.
676
+ - Returns: snake_case string.
677
+ - Notes: Punctuation within words is retained.
678
+ - Throws: `TypeError` if the input is not a string.
679
+
680
+ ### `truncate(str, length, suffix = "...")`
681
+
682
+ Limits a string to a maximum number of Unicode code points. If truncation is needed, the suffix is included within the requested maximum length.
683
+
684
+ ```js
685
+ truncate("JavaScript utilities", 12);
686
+ // "JavaScript..."
687
+
688
+ truncate("JavaScript utilities", 12, "…");
689
+ // "JavaScript …"
690
+
691
+ truncate("Developer", 5, "~");
692
+ // "Deve~"
693
+ ```
694
+
695
+ - `str` (`string`): Input string.
696
+ - `length` (`number`): Non-negative integer maximum length, including the suffix.
697
+ - `suffix` (`string`, optional): Suffix appended when truncation occurs; defaults to `"..."`.
698
+ - Returns: Truncated string or the original string if it already fits.
699
+ - Notes: If the suffix length is equal to or greater than `length`, the suffix itself is cut to fit. A length of `0` returns an empty string when truncation is needed.
700
+ - Throws: `TypeError` if `str` or `suffix` is not a string; `RangeError` if `length` is invalid.
701
+
702
+ ### `reverse(str)`
703
+
704
+ Reverses a string by Unicode code points.
705
+
706
+ ```js
707
+ reverse("hello"); // "olleh"
708
+ reverse("12345"); // "54321"
709
+ ```
710
+
711
+ - `str` (`string`): Input string.
712
+ - Returns: Reversed string.
713
+ - Notes: This is code-point-aware, but not grapheme-cluster-aware. Combining marks and joined emoji sequences may not remain visually grouped.
714
+ - Throws: `TypeError` if the input is not a string.
715
+
716
+ ### `countWords(str)`
717
+
718
+ Counts whitespace-separated tokens. Punctuation remains attached to each token and is not used to split words.
719
+
720
+ ```js
721
+ countWords("JavaScript is useful"); // 3
722
+ countWords(" Learn JavaScript today "); // 3
723
+ countWords(""); // 0
724
+ ```
725
+
726
+ - `str` (`string`): Input string.
727
+ - Returns: Number of whitespace-separated tokens.
728
+ - Throws: `TypeError` if the input is not a string.
729
+
730
+ ### `isPalindrome(str)`
731
+
732
+ Checks whether a string reads the same forward and backward after converting it to lowercase and removing all characters that are not Unicode letters or numbers.
733
+
734
+ ```js
735
+ isPalindrome("Racecar"); // true
736
+ isPalindrome("A man, a plan, a canal: Panama"); // true
737
+ isPalindrome("JavaScript"); // false
738
+ ```
739
+
740
+ - `str` (`string`): Input string.
741
+ - Returns: Boolean.
742
+ - Notes: Case, whitespace, and punctuation are ignored. An empty or punctuation-only string returns `true` because the normalized sequence is empty.
743
+ - Throws: `TypeError` if the input is not a string.
744
+
745
+ ## 4. Async utilities
746
+
747
+ Import from the package root:
748
+
749
+ ```js
750
+ import {
751
+ sleep,
752
+ retry,
753
+ withTimeout,
754
+ mapAsync,
755
+ pLimit,
756
+ debounceAsync,
757
+ promiseAllSettled,
758
+ } from "devcraft-js";
759
+ ```
760
+
761
+ ### `sleep(ms)`
762
+
763
+ Returns a promise that resolves after the specified number of milliseconds. It does not block the JavaScript event loop.
764
+
765
+ ```js
766
+ console.log("Before");
767
+ await sleep(500);
768
+ console.log("After 500 milliseconds");
769
+ ```
770
+
771
+ - `ms` (`number`): Finite, non-negative delay in milliseconds.
772
+ - Returns: `Promise<void>`.
773
+ - Throws: `RangeError` if the duration is invalid.
774
+
775
+ ### `retry(fn, options = {})`
776
+
777
+ Runs a synchronous or asynchronous function and retries it when it throws or rejects. The `retries` option counts additional attempts after the first attempt.
778
+
779
+ ```js
780
+ let attempts = 0;
781
+
782
+ const result = await retry(
783
+ async () => {
784
+ attempts += 1;
785
+
786
+ if (attempts < 3) {
787
+ throw new Error("Temporary failure");
788
+ }
789
+
790
+ return "Success";
791
+ },
792
+ {
793
+ retries: 3,
794
+ delay: 200,
795
+ backoff: 2,
796
+ },
797
+ );
798
+
799
+ console.log(result); // "Success"
800
+ console.log(attempts); // 3
801
+ ```
802
+
803
+ - `fn` (`Function`): Function to execute. It is called without arguments.
804
+ - `options` (`Object`, optional):
805
+ - `retries` (`number`, default `3`): Non-negative integer number of additional attempts.
806
+ - `delay` (`number`, default `1000`): Initial delay in milliseconds.
807
+ - `backoff` (`number`, default `1`): Non-negative multiplier applied to the delay after each failed attempt.
808
+ - Returns: A promise resolving to the function's result.
809
+ - Notes: Delays follow `delay * backoff ** attempt`, where the first retry uses `attempt = 0`. The final error is rethrown when retries are exhausted.
810
+ - Throws/rejects: `TypeError` for invalid function/options; `RangeError` for invalid retry or timing values; rejects with the final function error if all attempts fail.
811
+
812
+ ### `withTimeout(promise, ms)`
813
+
814
+ Waits for a promise-like value to settle, but rejects if the timeout duration elapses first.
815
+
816
+ ```js
817
+ const result = await withTimeout(
818
+ fetch("https://example.com"),
819
+ 5000,
820
+ );
821
+ ```
822
+
823
+ - `promise` (`Promise | any`): Promise or value to observe.
824
+ - `ms` (`number`): Finite, non-negative timeout in milliseconds.
825
+ - Returns: A promise that settles with the input result if it finishes before the timeout.
826
+ - Notes: A timeout does **not** cancel the underlying operation. The original operation may continue after the returned promise rejects.
827
+ - Rejects: With an `Error` containing the timeout duration if the timer fires, or with the original rejection reason if the input rejects.
828
+ - Throws: `RangeError` for an invalid timeout.
829
+
830
+ ### `mapAsync(array, fn, concurrency = Infinity)`
831
+
832
+ Maps an array with an asynchronous or synchronous callback while limiting the number of callbacks running at the same time. Results remain in input order, even if tasks finish in a different order.
833
+
834
+ ```js
835
+ const userIds = [1, 2, 3, 4, 5];
836
+
837
+ const users = await mapAsync(
838
+ userIds,
839
+ async (id) => {
840
+ const response = await fetch(`/api/users/${id}`);
841
+ return response.json();
842
+ },
843
+ 2,
844
+ );
845
+ ```
846
+
847
+ - `array` (`Array`): Input array.
848
+ - `fn` (`Function`): Callback called with `(value, index, array)`.
849
+ - `concurrency` (`number`, optional): Positive integer limit or `Infinity`; defaults to `Infinity`.
850
+ - Returns: A promise resolving to a result array in input order.
851
+ - Notes: If a callback fails, the returned promise rejects and no new work is scheduled by workers that have not yet started another item. Callbacks already running continue.
852
+ - Throws/rejects: `TypeError` for invalid array or callback; `RangeError` for invalid concurrency; rejects if a callback rejects.
853
+
854
+ ### `pLimit(concurrency)`
855
+
856
+ Creates a reusable function that schedules tasks with a maximum number of concurrently running operations.
857
+
858
+ ```js
859
+ const limit = pLimit(2);
860
+
861
+ const tasks = [1, 2, 3, 4].map((number) =>
862
+ limit(async (value) => {
863
+ await sleep(200);
864
+ return value * 2;
865
+ }, number),
866
+ );
867
+
868
+ const results = await Promise.all(tasks);
869
+
870
+ console.log(results); // [2, 4, 6, 8]
871
+ ```
872
+
873
+ - `concurrency` (`number`): Positive integer maximum number of active tasks.
874
+ - Returns: A limiter function. Call it as `limit(fn, ...args)` to queue a function and pass arguments to it.
875
+ - The returned call produces a promise for that task's result.
876
+ - Notes: Synchronous exceptions thrown by a task become promise rejections. Tasks are started in queue order.
877
+ - Throws: `RangeError` if concurrency is not a positive integer; the limiter call throws `TypeError` if its callback is not a function.
878
+
879
+ ### `debounceAsync(fn, delay)`
880
+
881
+ Debounces asynchronous function calls. When several calls occur within the delay window, the wrapped function runs once using the latest call's arguments and `this` context. Every pending caller receives the same result or rejection from that execution.
882
+
883
+ ```js
884
+ const search = debounceAsync(
885
+ async (query) => {
886
+ const response = await fetch(`/search?q=${encodeURIComponent(query)}`);
887
+ return response.json();
888
+ },
889
+ 300,
890
+ );
891
+
892
+ const first = search("jav");
893
+ const second = search("javascript");
894
+
895
+ const [firstResult, secondResult] = await Promise.all([first, second]);
896
+ // Both promises receive the result for "javascript".
897
+ ```
898
+
899
+ - `fn` (`Function`): Function to invoke after the calls settle.
900
+ - `delay` (`number`): Finite, non-negative delay in milliseconds.
901
+ - Returns: A debounced function that returns a promise for each call.
902
+ - Notes: All calls in the same debounce window settle with the result of the latest invocation.
903
+ - Throws: `TypeError` if `fn` is not a function; `RangeError` for an invalid delay. The returned promises reject if the wrapped function rejects.
904
+
905
+ ### `promiseAllSettled(promises)`
906
+
907
+ A convenience wrapper around `Promise.allSettled()`. It fulfills with an outcome record for every input promise or value, preserving input order.
908
+
909
+ ```js
910
+ const results = await promiseAllSettled([
911
+ Promise.resolve("success"),
912
+ Promise.reject(new Error("failure")),
913
+ 42,
914
+ ]);
915
+
916
+ console.log(results);
917
+ // [
918
+ // { status: "fulfilled", value: "success" },
919
+ // { status: "rejected", reason: Error("failure") },
920
+ // { status: "fulfilled", value: 42 }
921
+ // ]
922
+ ```
923
+
924
+ - `promises` (`Iterable`): Iterable of promises or ordinary values.
925
+ - Returns: The same kind of result as `Promise.allSettled()`.
926
+ - Throws: `TypeError` if the input is null, undefined, or not iterable.
927
+
928
+ ## 5. Function utilities
929
+
930
+ Import from the package root:
931
+
932
+ ```js
933
+ import {
934
+ once,
935
+ memoize,
936
+ curry,
937
+ compose,
938
+ pipe,
939
+ partial,
940
+ debounce,
941
+ } from "devcraft-js";
942
+ ```
943
+
944
+ ### `once(fn)`
945
+
946
+ Creates a wrapper that invokes a function at most once and returns the first successful return value on later calls.
947
+
948
+ ```js
949
+ let calls = 0;
950
+
951
+ const initialize = once(() => {
952
+ calls += 1;
953
+ return "initialized";
954
+ });
955
+
956
+ initialize(); // "initialized"
957
+ initialize(); // "initialized"
958
+
959
+ console.log(calls); // 1
960
+ ```
961
+
962
+ - `fn` (`Function`): Function to wrap.
963
+ - Returns: A function that caches the first returned value.
964
+ - Notes: If `fn` throws synchronously, the result is not cached and a later call can retry. If `fn` returns a promise that later rejects, that returned promise has already been cached.
965
+ - Throws: `TypeError` if `fn` is not a function; propagates synchronous errors from `fn`.
966
+
967
+ ### `memoize(fn, options = {})`
968
+
969
+ Caches function results so repeated calls with the same receiver and arguments can reuse a previous result. By default, arguments are cached by their JavaScript `Map` key identity/value semantics. An optional resolver can generate a single cache key from the arguments.
970
+
971
+ ```js
972
+ const calculate = memoize((number) => {
973
+ console.log("Calculating...");
974
+ return number * number;
975
+ });
976
+
977
+ calculate(5); // Logs "Calculating...", returns 25
978
+ calculate(5); // Returns cached 25
979
+ ```
980
+
981
+ Using a resolver:
982
+
983
+ ```js
984
+ const getUser = memoize(
985
+ (id, includePosts) => ({ id, includePosts }),
986
+ {
987
+ resolver: (id, includePosts) => `${id}:${includePosts}`,
988
+ },
989
+ );
990
+
991
+ getUser(7, true);
992
+ getUser(7, true); // Uses the cached result.
993
+ ```
994
+
995
+ - `fn` (`Function`): Function whose results should be cached.
996
+ - `options` (`Object`, optional):
997
+ - `resolver` (`Function`, optional): Called with the same receiver and arguments; its return value is used as the cache key.
998
+ - Returns: A memoized function.
999
+ - Notes:
1000
+ - Cache entries are separated by the call-time `this` receiver.
1001
+ - Without a resolver, each argument is used as a key in a nested `Map` cache.
1002
+ - The implementation does not expose cache clearing or automatic eviction.
1003
+ - Rejected promises returned by an async function are cached as returned values.
1004
+ - Throws: `TypeError` if the function, options, or resolver is invalid; propagates errors from the wrapped function or resolver.
1005
+
1006
+ ### `curry(fn)`
1007
+
1008
+ Transforms a function into a curried function. Arguments can be supplied across multiple calls until the original function's declared arity (`fn.length`) is reached. Any additional arguments in the call that reaches the arity are passed through as well.
1009
+
1010
+ ```js
1011
+ function add(a, b, c) {
1012
+ return a + b + c;
1013
+ }
1014
+
1015
+ const curriedAdd = curry(add);
1016
+
1017
+ curriedAdd(1)(2)(3); // 6
1018
+ curriedAdd(1, 2)(3); // 6
1019
+ curriedAdd(1)(2, 3); // 6
1020
+ ```
1021
+
1022
+ - `fn` (`Function`): Function to curry.
1023
+ - Returns: A curried function.
1024
+ - Notes: Arity is based on `fn.length`. A function with arity `0` is returned as a wrapper that invokes the original function immediately. The implementation does not provide placeholder arguments.
1025
+ - Throws: `TypeError` if `fn` is not a function.
1026
+
1027
+ ### `compose(...functions)`
1028
+
1029
+ Creates a function that applies the supplied functions from right to left. The rightmost function receives the initial arguments; each function to its left receives the previous result.
1030
+
1031
+ ```js
1032
+ const addOne = (value) => value + 1;
1033
+ const double = (value) => value * 2;
1034
+
1035
+ const transform = compose(addOne, double);
1036
+
1037
+ transform(3); // 7: addOne(double(3))
1038
+ ```
1039
+
1040
+ - `functions` (`...Function[]`): Functions to compose.
1041
+ - Returns: A composed function.
1042
+ - Notes: Composition is synchronous. Promise values are passed to the next function as ordinary values; they are not automatically awaited. With no functions, the returned function returns its first argument.
1043
+ - Throws: `TypeError` if any supplied item is not a function.
1044
+
1045
+ ### `pipe(...functions)`
1046
+
1047
+ Creates a function that applies the supplied functions from left to right. The leftmost function receives the initial arguments; each later function receives the previous result.
1048
+
1049
+ ```js
1050
+ const addOne = (value) => value + 1;
1051
+ const double = (value) => value * 2;
1052
+
1053
+ const transform = pipe(addOne, double);
1054
+
1055
+ transform(3); // 8: double(addOne(3))
1056
+ ```
1057
+
1058
+ - `functions` (`...Function[]`): Functions to pipe.
1059
+ - Returns: A piped function.
1060
+ - Notes: Piping is synchronous. Promise values are not automatically awaited. With no functions, the returned function returns its first argument.
1061
+ - Throws: `TypeError` if any supplied item is not a function.
1062
+
1063
+ ### `partial(fn, ...presetArguments)`
1064
+
1065
+ Creates a function with preset arguments. Preset arguments are placed before the arguments supplied when the returned function is called.
1066
+
1067
+ ```js
1068
+ function greet(greeting, name) {
1069
+ return `${greeting}, ${name}!`;
1070
+ }
1071
+
1072
+ const sayHello = partial(greet, "Hello");
1073
+
1074
+ sayHello("Asha"); // "Hello, Asha!"
1075
+ ```
1076
+
1077
+ - `fn` (`Function`): Function to partially apply.
1078
+ - `presetArguments` (`...any[]`): Arguments to provide before later arguments.
1079
+ - Returns: A partially applied function.
1080
+ - Notes: The call-time `this` receiver is preserved. This implementation does not use placeholder arguments.
1081
+ - Throws: `TypeError` if `fn` is not a function; propagates errors from `fn`.
1082
+
1083
+ ### `debounce(fn, delay)`
1084
+
1085
+ Creates a debounced function that delays invocation until calls have stopped for the specified duration. If called repeatedly during the delay, only the latest call is executed with its arguments and receiver.
1086
+
1087
+ ```js
1088
+ const saveDraft = debounce((text) => {
1089
+ console.log("Saving:", text);
1090
+ }, 500);
1091
+
1092
+ saveDraft("First version");
1093
+ saveDraft("Updated version");
1094
+ // After 500 ms without another call: "Saving: Updated version"
1095
+ ```
1096
+
1097
+ - `fn` (`Function`): Function to debounce.
1098
+ - `delay` (`number`): Finite, non-negative delay in milliseconds.
1099
+ - Returns: A debounced function.
1100
+ - Notes: The wrapper returns `undefined` immediately. It does not expose `cancel()` or `flush()` methods.
1101
+ - Throws: `TypeError` if `fn` is not a function; `RangeError` if delay is invalid.
1102
+
1103
+ ## 6. Validation utilities
1104
+
1105
+ Import from the package root:
1106
+
1107
+ ```js
1108
+ import {
1109
+ isEmail,
1110
+ isURL,
1111
+ isPhoneNumber,
1112
+ isStrongPassword,
1113
+ isEmpty,
1114
+ isNumeric,
1115
+ isJSON,
1116
+ isAlpha,
1117
+ isAlphanumeric,
1118
+ } from "devcraft-js";
1119
+ ```
1120
+
1121
+ Validation helpers return booleans for the values they inspect, except that invalid options supplied to `isStrongPassword` cause an error.
1122
+
1123
+ ### `isEmail(value)`
1124
+
1125
+ Checks common email-address syntax. It does not send a message or verify that the address exists or can receive email.
1126
+
1127
+ ```js
1128
+ isEmail("developer@example.com"); // true
1129
+ isEmail("not-an-email"); // false
1130
+ isEmail(" user@example.com "); // false
1131
+ ```
1132
+
1133
+ - `value` (`any`): Value to inspect.
1134
+ - Returns: Boolean.
1135
+ - Notes: Requires one `@`, a non-empty local part, and a domain with at least two valid labels. Leading/trailing whitespace is rejected.
1136
+
1137
+ ### `isURL(value)`
1138
+
1139
+ Checks whether a string is an absolute HTTP or HTTPS URL with a valid hostname according to the implementation's checks. `localhost` is allowed.
1140
+
1141
+ ```js
1142
+ isURL("https://example.com"); // true
1143
+ isURL("http://localhost:3000"); // true
1144
+ isURL("ftp://example.com"); // false
1145
+ isURL("http://-invalid.com"); // false
1146
+ ```
1147
+
1148
+ - `value` (`any`): Value to inspect.
1149
+ - Returns: Boolean.
1150
+ - Notes: A protocol is required. Only `http:` and `https:` are accepted. This is syntax validation, not a network request or proof that the destination is reachable.
1151
+
1152
+ ### `isPhoneNumber(value)`
1153
+
1154
+ Checks a general phone-number format containing 7 to 15 digits. It permits an optional leading plus sign, spaces, hyphens, and one balanced pair of parentheses around digits.
1155
+
1156
+ ```js
1157
+ isPhoneNumber("+1 (555) 123-4567"); // true
1158
+ isPhoneNumber("555-123-4567"); // true
1159
+ isPhoneNumber("12345"); // false
1160
+ isPhoneNumber("12(34)56)"); // false
1161
+ ```
1162
+
1163
+ - `value` (`any`): Value to inspect.
1164
+ - Returns: Boolean.
1165
+ - Notes: It does not verify country-specific numbering plans, assignment, ownership, or reachability.
1166
+
1167
+ ### `isStrongPassword(value, options = {})`
1168
+
1169
+ Checks a string against configurable password composition rules.
1170
+
1171
+ ```js
1172
+ isStrongPassword("Secure@123");
1173
+ // true with the default rules
1174
+
1175
+ isStrongPassword("javascript", {
1176
+ minLength: 10,
1177
+ requireUppercase: false,
1178
+ requireLowercase: true,
1179
+ requireNumbers: false,
1180
+ requireSpecialChars: false,
1181
+ });
1182
+ // true
1183
+ ```
1184
+
1185
+ Default options:
1186
+
1187
+ | Option | Default | Meaning |
1188
+ | --- | --- | --- |
1189
+ | `minLength` | `8` | Minimum number of Unicode code points |
1190
+ | `requireUppercase` | `true` | Requires at least one uppercase Unicode letter |
1191
+ | `requireLowercase` | `true` | Requires at least one lowercase Unicode letter |
1192
+ | `requireNumbers` | `true` | Requires at least one Unicode number |
1193
+ | `requireSpecialChars` | `true` | Requires at least one character that is neither a Unicode letter nor number |
1194
+
1195
+ - `value` (`any`): Value to inspect.
1196
+ - `options` (`Object`, optional): Overrides for the rules above.
1197
+ - Returns: Boolean indicating whether all enabled rules pass.
1198
+ - Throws: `TypeError` for invalid options or non-boolean rule flags; `RangeError` if `minLength` is not a positive integer.
1199
+ - Notes: This checks composition rules only. It is not a password-strength estimator and does not check breached-password databases.
1200
+
1201
+ ### `isEmpty(value)`
1202
+
1203
+ Checks whether a value is empty according to the following rules:
1204
+
1205
+ - `null` and `undefined` are empty.
1206
+ - Strings containing only whitespace are empty.
1207
+ - Arrays with length `0` are empty.
1208
+ - Plain objects with no own enumerable string-keyed properties are empty.
1209
+ - Other values, including numbers and booleans, are not empty.
1210
+
1211
+ ```js
1212
+ isEmpty(null); // true
1213
+ isEmpty(" "); // true
1214
+ isEmpty([]); // true
1215
+ isEmpty({}); // true
1216
+ isEmpty(0); // false
1217
+ isEmpty(false); // false
1218
+ isEmpty({ name: "A" }); // false
1219
+ ```
1220
+
1221
+ - `value` (`any`): Value to inspect.
1222
+ - Returns: Boolean.
1223
+
1224
+ ### `isNumeric(value)`
1225
+
1226
+ Checks whether a value is a finite number or a non-empty string that converts to a finite number with JavaScript's `Number()` conversion.
1227
+
1228
+ ```js
1229
+ isNumeric(42); // true
1230
+ isNumeric("42"); // true
1231
+ isNumeric(" 42 "); // true
1232
+ isNumeric("1e3"); // true
1233
+ isNumeric("0xFF"); // true
1234
+ isNumeric("hello"); // false
1235
+ isNumeric(""); // false
1236
+ isNumeric(Infinity); // false
1237
+ ```
1238
+
1239
+ - `value` (`any`): Value to inspect.
1240
+ - Returns: Boolean.
1241
+ - Notes: JavaScript numeric string forms accepted by `Number()` are accepted, including hexadecimal and scientific notation. Empty/whitespace-only strings and non-finite numbers are rejected.
1242
+
1243
+ ### `isJSON(value)`
1244
+
1245
+ Checks whether a string can be parsed by `JSON.parse()`. It does not execute JavaScript.
1246
+
1247
+ ```js
1248
+ isJSON('{"name":"Asha"}'); // true
1249
+ isJSON("[1, 2, 3]"); // true
1250
+ isJSON("{name: 'Asha'}"); // false
1251
+ isJSON("undefined"); // false
1252
+ ```
1253
+
1254
+ - `value` (`any`): Value to inspect.
1255
+ - Returns: Boolean.
1256
+ - Notes: Valid JSON primitives such as `"42"`, `"true"`, and `"null"` are accepted because `JSON.parse()` accepts them.
1257
+
1258
+ ### `isAlpha(value)`
1259
+
1260
+ Checks whether a non-empty string contains only Unicode letters. Whitespace, numbers, and punctuation are not accepted.
1261
+
1262
+ ```js
1263
+ isAlpha("Developer"); // true
1264
+ isAlpha("Utkarsh"); // true
1265
+ isAlpha("User123"); // false
1266
+ isAlpha("Hello!"); // false
1267
+ ```
1268
+
1269
+ - `value` (`any`): Value to inspect.
1270
+ - Returns: Boolean.
1271
+ - Notes: The string is not trimmed; leading or trailing whitespace causes the check to fail.
1272
+
1273
+ ### `isAlphanumeric(value)`
1274
+
1275
+ Checks whether a non-empty string contains only Unicode letters and numbers.
1276
+
1277
+ ```js
1278
+ isAlphanumeric("User123"); // true
1279
+ isAlphanumeric("2026"); // true
1280
+ isAlphanumeric("User_123"); // false
1281
+ isAlphanumeric("Hello!"); // false
1282
+ ```
1283
+
1284
+ - `value` (`any`): Value to inspect.
1285
+ - Returns: Boolean.
1286
+ - Notes: The string is not trimmed; whitespace and punctuation are rejected.
1287
+
1288
+ ## Error handling and behavior notes
1289
+
1290
+ Many utilities validate their inputs and throw a `TypeError` or `RangeError` when an argument has an invalid type or value. Validation helpers generally return `false` for values that do not satisfy their checks.
1291
+
1292
+ A few important behavior distinctions:
1293
+
1294
+ - **Mutation:** `set()` intentionally mutates its root object. Most array helpers return new arrays. `deepMerge()` returns a new object and does not mutate its inputs.
1295
+ - **Shallow versus deep:** `chunk()`, `shuffle()`, `pick()`, and `omit()` do not deep-clone nested values.
1296
+ - **Equality:** `unique()`, `difference()`, and the key tracking used by `uniqueBy()` use `Set` semantics. Objects are compared by reference unless a callback computes another key.
1297
+ - **Async cancellation:** `withTimeout()` stops waiting after the timeout but does not cancel the underlying operation.
1298
+ - **Debouncing:** `debounce()` returns immediately with `undefined`; `debounceAsync()` returns promises to callers and shares the latest invocation's outcome.
1299
+ - **Function pipelines:** `compose()` and `pipe()` do not automatically await promises.
1300
+ - **Validation scope:** Email, URL, phone, and password helpers perform local format/rule checks. They do not verify real-world identity, deliverability, reachability, or password safety against external databases.
1301
+
1302
+ ## Module formats
1303
+
1304
+ DevCraft JS publishes two builds:
1305
+
1306
+ | File | Format | Typical consumer |
1307
+ | --- | --- | --- |
1308
+ | `dist/index.js` | ES module | `import { chunk } from "devcraft-js"` |
1309
+ | `dist/index.cjs` | CommonJS | `const { chunk } = require("devcraft-js")` |
1310
+
1311
+ The package uses the `exports` field in `package.json` to route ESM `import` and CommonJS `require` consumers to the appropriate build.
1312
+
1313
+ ## Project structure
1314
+
1315
+ ```text
1316
+ devcraft-js/
1317
+ ├── src/
1318
+ │ ├── array/
1319
+ │ │ ├── array.js
1320
+ │ │ └── index.js
1321
+ │ ├── async/
1322
+ │ │ ├── async.js
1323
+ │ │ └── index.js
1324
+ │ ├── function/
1325
+ │ │ ├── function.js
1326
+ │ │ └── index.js
1327
+ │ ├── object/
1328
+ │ │ ├── object.js
1329
+ │ │ └── index.js
1330
+ │ ├── string/
1331
+ │ │ ├── string.js
1332
+ │ │ └── index.js
1333
+ │ ├── validation/
1334
+ │ │ ├── validation.js
1335
+ │ │ └── index.js
1336
+ │ └── index.js
1337
+ ├── tests/
1338
+ │ ├── array.test.js
1339
+ │ ├── async.test.js
1340
+ │ ├── function.test.js
1341
+ │ ├── object.test.js
1342
+ │ ├── string.test.js
1343
+ │ └── validation.test.js
1344
+ ├── dist/
1345
+ │ ├── index.js
1346
+ │ └── index.cjs
1347
+ ├── package.json
1348
+ ├── package-lock.json
1349
+ ├── README.md
1350
+ └── LICENSE
1351
+ ```
1352
+
1353
+ ## Development
1354
+
1355
+ Clone the repository and install development dependencies:
1356
+
1357
+ ```bash
1358
+ git clone https://github.com/Utkarsh12072007/DevCraft-JS.git
1359
+ cd DevCraft-JS
1360
+ npm install
1361
+ ```
1362
+
1363
+ Build both module formats:
1364
+
1365
+ ```bash
1366
+ npm run build
1367
+ ```
1368
+
1369
+ The build command uses tsup to bundle `src/index.js` into:
1370
+
1371
+ - `dist/index.js` (ESM)
1372
+ - `dist/index.cjs` (CommonJS)
1373
+
1374
+ The build script cleans the previous `dist` directory before generating fresh output.
1375
+
1376
+ ## Testing
1377
+
1378
+ Run the complete test suite:
1379
+
1380
+ ```bash
1381
+ npm test
1382
+ ```
1383
+
1384
+ Run Vitest in watch mode while developing:
1385
+
1386
+ ```bash
1387
+ npm run test:watch
1388
+ ```
1389
+
1390
+ The repository contains separate test files for the six utility modules.
1391
+
1392
+ ## Testing a packed installation
1393
+
1394
+ To check the package as a consumer would receive it:
1395
+
1396
+ 1. Build the package:
1397
+
1398
+ ```bash
1399
+ npm run build
1400
+ ```
1401
+
1402
+ 2. Create a package archive:
1403
+
1404
+ ```bash
1405
+ npm pack
1406
+ ```
1407
+
1408
+ 3. Create a separate test project:
1409
+
1410
+ ```bash
1411
+ mkdir devcraft-js-smoke-test
1412
+ cd devcraft-js-smoke-test
1413
+ npm init -y
1414
+ ```
1415
+
1416
+ 4. Install the `.tgz` archive created in the package directory:
1417
+
1418
+ ```bash
1419
+ npm install ../devcraft-js/devcraft-js-0.1.0.tgz
1420
+ ```
1421
+
1422
+ Adjust the relative path if your folders are in a different location.
1423
+
1424
+ 5. Test ESM in an `.mjs` file:
1425
+
1426
+ ```js
1427
+ import { chunk, isEmail } from "devcraft-js";
1428
+
1429
+ console.log(chunk([1, 2, 3], 2));
1430
+ console.log(isEmail("developer@example.com"));
1431
+ ```
1432
+
1433
+ 6. Test CommonJS in a `.cjs` file:
1434
+
1435
+ ```js
1436
+ const { unique, capitalize } = require("devcraft-js");
1437
+
1438
+ console.log(unique([1, 1, 2]));
1439
+ console.log(capitalize("hello"));
1440
+ ```
1441
+
1442
+ This verifies the packed artifact rather than importing directly from the source directory.
1443
+
1444
+ ## Contributing
1445
+
1446
+ Contributions, bug reports, and suggestions are welcome.
1447
+
1448
+ Before opening a pull request:
1449
+
1450
+ 1. Create a focused branch for your change.
1451
+ 2. Keep changes limited to the relevant utility or module.
1452
+ 3. Add or update tests for changed behavior.
1453
+ 4. Run `npm test`.
1454
+ 5. Run `npm run build`.
1455
+ 6. Update the README if the public API or behavior changes.
1456
+ 7. Open a pull request describing the change and its tests.
1457
+
1458
+ For bugs or feature requests, use the repository's GitHub Issues page.
1459
+
1460
+ ## License
1461
+
1462
+ This project is intended to be released under the **MIT License**. See the [`LICENSE`](./LICENSE) file for the full license text.