@absoluteui/helpers 0.0.0-stage → 0.13.2
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/LICENSE +201 -0
- package/NOTICE +5 -0
- package/README.md +47 -2
- package/SECURITY.md +102 -0
- package/dist/array/compare.d.ts +8 -0
- package/dist/array/compare.js +2 -0
- package/dist/array/index.d.ts +328 -0
- package/dist/array/index.js +2 -0
- package/dist/array/tree.d.ts +48 -0
- package/dist/array/tree.js +2 -0
- package/dist/async/batch.d.ts +103 -0
- package/dist/async/batch.js +2 -0
- package/dist/async/concurrency.d.ts +92 -0
- package/dist/async/concurrency.js +2 -0
- package/dist/async/control.d.ts +77 -0
- package/dist/async/control.js +2 -0
- package/dist/async/index.d.ts +8 -0
- package/dist/async/index.js +2 -0
- package/dist/async/signal.d.ts +95 -0
- package/dist/async/signal.js +2 -0
- package/dist/boolean/index.d.ts +83 -0
- package/dist/boolean/index.js +2 -0
- package/dist/business-calendar/days.d.ts +397 -0
- package/dist/business-calendar/days.js +2 -0
- package/dist/business-calendar/describe.d.ts +45 -0
- package/dist/business-calendar/describe.js +2 -0
- package/dist/business-calendar/engine.d.ts +305 -0
- package/dist/business-calendar/engine.js +2 -0
- package/dist/business-calendar/hours.d.ts +96 -0
- package/dist/business-calendar/hours.js +2 -0
- package/dist/business-calendar/index.d.ts +29 -0
- package/dist/business-calendar/index.js +2 -0
- package/dist/business-calendar/internal.d.ts +44 -0
- package/dist/business-calendar/internal.js +2 -0
- package/dist/business-calendar/rules.d.ts +260 -0
- package/dist/business-calendar/rules.js +2 -0
- package/dist/color/index.d.ts +200 -0
- package/dist/color/index.js +2 -0
- package/dist/color/named.d.ts +4 -0
- package/dist/color/named.js +2 -0
- package/dist/compare/index.d.ts +186 -0
- package/dist/compare/index.js +2 -0
- package/dist/convert/index.d.ts +152 -0
- package/dist/convert/index.js +2 -0
- package/dist/csv/index.d.ts +6 -0
- package/dist/csv/index.js +2 -0
- package/dist/csv/parse.d.ts +85 -0
- package/dist/csv/parse.js +12 -0
- package/dist/csv/stringify.d.ts +48 -0
- package/dist/csv/stringify.js +5 -0
- package/dist/date/calendar.d.ts +339 -0
- package/dist/date/calendar.js +2 -0
- package/dist/date/format.d.ts +66 -0
- package/dist/date/format.js +2 -0
- package/dist/date/index.d.ts +26 -0
- package/dist/date/index.js +2 -0
- package/dist/date/intervals.d.ts +110 -0
- package/dist/date/intervals.js +2 -0
- package/dist/date/intl-cache.d.ts +10 -0
- package/dist/date/intl-cache.js +2 -0
- package/dist/date/locale.d.ts +58 -0
- package/dist/date/locale.js +2 -0
- package/dist/date/plain-date.d.ts +105 -0
- package/dist/date/plain-date.js +2 -0
- package/dist/date/plain-time.d.ts +121 -0
- package/dist/date/plain-time.js +2 -0
- package/dist/date/zone.d.ts +121 -0
- package/dist/date/zone.js +2 -0
- package/dist/decimal/index.d.ts +149 -0
- package/dist/decimal/index.js +2 -0
- package/dist/ds/avl.d.ts +50 -0
- package/dist/ds/avl.js +2 -0
- package/dist/ds/bitset.d.ts +46 -0
- package/dist/ds/bitset.js +2 -0
- package/dist/ds/bloom.d.ts +41 -0
- package/dist/ds/bloom.js +2 -0
- package/dist/ds/caches.d.ts +141 -0
- package/dist/ds/caches.js +2 -0
- package/dist/ds/disjoint-set.d.ts +38 -0
- package/dist/ds/disjoint-set.js +2 -0
- package/dist/ds/emitter.d.ts +53 -0
- package/dist/ds/emitter.js +2 -0
- package/dist/ds/graph.d.ts +84 -0
- package/dist/ds/graph.js +2 -0
- package/dist/ds/heap.d.ts +49 -0
- package/dist/ds/heap.js +2 -0
- package/dist/ds/index.d.ts +20 -0
- package/dist/ds/index.js +2 -0
- package/dist/ds/internal.d.ts +19 -0
- package/dist/ds/internal.js +2 -0
- package/dist/ds/interval-tree.d.ts +49 -0
- package/dist/ds/interval-tree.js +2 -0
- package/dist/ds/linked-list.d.ts +54 -0
- package/dist/ds/linked-list.js +2 -0
- package/dist/ds/maps.d.ts +89 -0
- package/dist/ds/maps.js +2 -0
- package/dist/ds/ring.d.ts +99 -0
- package/dist/ds/ring.js +2 -0
- package/dist/ds/sorted.d.ts +104 -0
- package/dist/ds/sorted.js +2 -0
- package/dist/ds/stack.d.ts +28 -0
- package/dist/ds/stack.js +2 -0
- package/dist/ds/trie.d.ts +84 -0
- package/dist/ds/trie.js +2 -0
- package/dist/duration/index.d.ts +146 -0
- package/dist/duration/index.js +2 -0
- package/dist/encoding/index.d.ts +144 -0
- package/dist/encoding/index.js +2 -0
- package/dist/error/index.d.ts +316 -0
- package/dist/error/index.js +2 -0
- package/dist/fn/index.d.ts +129 -0
- package/dist/fn/index.js +2 -0
- package/dist/fn/memo.d.ts +46 -0
- package/dist/fn/memo.js +2 -0
- package/dist/fn/timing.d.ts +64 -0
- package/dist/fn/timing.js +2 -0
- package/dist/http/headers.d.ts +160 -0
- package/dist/http/headers.js +2 -0
- package/dist/http/index.d.ts +10 -0
- package/dist/http/index.js +2 -0
- package/dist/http/problem.d.ts +37 -0
- package/dist/http/problem.js +2 -0
- package/dist/http/response.d.ts +43 -0
- package/dist/http/response.js +2 -0
- package/dist/http/status.d.ts +169 -0
- package/dist/http/status.js +2 -0
- package/dist/index.d.ts +34 -0
- package/dist/index.js +2 -0
- package/dist/internal/keys.d.ts +6 -0
- package/dist/internal/keys.js +2 -0
- package/dist/is/index.d.ts +219 -0
- package/dist/is/index.js +2 -0
- package/dist/json/index.d.ts +9 -0
- package/dist/json/index.js +2 -0
- package/dist/json/internal.d.ts +12 -0
- package/dist/json/internal.js +2 -0
- package/dist/json/ndjson.d.ts +28 -0
- package/dist/json/ndjson.js +4 -0
- package/dist/json/parse.d.ts +45 -0
- package/dist/json/parse.js +2 -0
- package/dist/json/patch.d.ts +62 -0
- package/dist/json/patch.js +2 -0
- package/dist/json/pointer.d.ts +43 -0
- package/dist/json/pointer.js +2 -0
- package/dist/json/stringify.d.ts +42 -0
- package/dist/json/stringify.js +2 -0
- package/dist/linq/enumerable.d.ts +208 -0
- package/dist/linq/enumerable.js +2 -0
- package/dist/linq/index.d.ts +6 -0
- package/dist/linq/index.js +2 -0
- package/dist/linq/operators.d.ts +503 -0
- package/dist/linq/operators.js +2 -0
- package/dist/number/core.d.ts +164 -0
- package/dist/number/core.js +2 -0
- package/dist/number/format.d.ts +80 -0
- package/dist/number/format.js +2 -0
- package/dist/number/index.d.ts +12 -0
- package/dist/number/index.js +2 -0
- package/dist/number/internal.d.ts +18 -0
- package/dist/number/internal.js +2 -0
- package/dist/number/parse.d.ts +45 -0
- package/dist/number/parse.js +2 -0
- package/dist/number/words.d.ts +19 -0
- package/dist/number/words.js +2 -0
- package/dist/object/basic.d.ts +130 -0
- package/dist/object/basic.js +2 -0
- package/dist/object/deep.d.ts +90 -0
- package/dist/object/deep.js +2 -0
- package/dist/object/diff.d.ts +57 -0
- package/dist/object/diff.js +2 -0
- package/dist/object/index.d.ts +8 -0
- package/dist/object/index.js +2 -0
- package/dist/object/internal.d.ts +21 -0
- package/dist/object/internal.js +2 -0
- package/dist/object/path.d.ts +17 -0
- package/dist/object/path.js +2 -0
- package/dist/random/core.d.ts +14 -0
- package/dist/random/core.js +2 -0
- package/dist/random/index.d.ts +167 -0
- package/dist/random/index.js +2 -0
- package/dist/random/seeded.d.ts +27 -0
- package/dist/random/seeded.js +2 -0
- package/dist/sanitize/index.d.ts +8 -0
- package/dist/sanitize/index.js +2 -0
- package/dist/sanitize/pii.d.ts +48 -0
- package/dist/sanitize/pii.js +2 -0
- package/dist/sanitize/records.d.ts +100 -0
- package/dist/sanitize/records.js +2 -0
- package/dist/sanitize/text.d.ts +101 -0
- package/dist/sanitize/text.js +2 -0
- package/dist/set/index.d.ts +162 -0
- package/dist/set/index.js +2 -0
- package/dist/stats/index.d.ts +190 -0
- package/dist/stats/index.js +2 -0
- package/dist/string/index.d.ts +494 -0
- package/dist/string/index.js +8 -0
- package/dist/string/internal.d.ts +33 -0
- package/dist/string/internal.js +2 -0
- package/dist/string/words.d.ts +14 -0
- package/dist/string/words.js +2 -0
- package/dist/timezone/index.d.ts +76 -0
- package/dist/timezone/index.js +2 -0
- package/dist/url/index.d.ts +178 -0
- package/dist/url/index.js +2 -0
- package/dist/validate/builders.d.ts +6 -0
- package/dist/validate/builders.js +2 -0
- package/dist/validate/formats.d.ts +237 -0
- package/dist/validate/formats.js +2 -0
- package/dist/validate/index.d.ts +13 -0
- package/dist/validate/index.js +2 -0
- package/dist/validate/schema.d.ts +220 -0
- package/dist/validate/schema.js +2 -0
- package/dist/zip/index.d.ts +8 -0
- package/dist/zip/index.js +2 -0
- package/dist/zip/internal.d.ts +69 -0
- package/dist/zip/internal.js +2 -0
- package/dist/zip/reader.d.ts +56 -0
- package/dist/zip/reader.js +2 -0
- package/dist/zip/writer.d.ts +65 -0
- package/dist/zip/writer.js +2 -0
- package/package.json +150 -4
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
export { buildTree, flattenTree } from './tree.js';
|
|
2
|
+
export type { BuildTreeOptions, BuildTreeResult, FlattenTreeOptions, FlatTreeEntry, TreeNode } from './tree.js';
|
|
3
|
+
/** Maximum element count produced by `range`, `times`, and `repeat`. */
|
|
4
|
+
export declare const MAX_GENERATED_LENGTH = 10000000;
|
|
5
|
+
/** Element comparer: negative, zero, or positive. */
|
|
6
|
+
export type Comparer<T> = (a: T, b: T) => number;
|
|
7
|
+
/**
|
|
8
|
+
* Splits into chunks of `size`; the last chunk may be shorter.
|
|
9
|
+
* @example
|
|
10
|
+
* chunk([1, 2, 3, 4, 5], 2); // => [[1, 2], [3, 4], [5]]
|
|
11
|
+
*/
|
|
12
|
+
export declare function chunk<T>(items: readonly T[], size: number): T[][];
|
|
13
|
+
/**
|
|
14
|
+
* Splits into `[matching, rest]`, preserving order.
|
|
15
|
+
* @example
|
|
16
|
+
* partition([1, 2, 3, 4], (n) => n % 2 === 0); // => [[2, 4], [1, 3]]
|
|
17
|
+
*/
|
|
18
|
+
export declare function partition<T, S extends T>(items: readonly T[], predicate: (item: T, index: number) => item is S): [S[], Exclude<T, S>[]];
|
|
19
|
+
export declare function partition<T>(items: readonly T[], predicate: (item: T, index: number) => boolean): [T[], T[]];
|
|
20
|
+
/**
|
|
21
|
+
* Groups into a null-prototype record keyed by `keyFn` (native `Object.groupBy` when present).
|
|
22
|
+
* @example
|
|
23
|
+
* groupBy(['one', 'two', 'three'], (s) => s.length); // => { 3: ['one', 'two'], 5: ['three'] }
|
|
24
|
+
*/
|
|
25
|
+
export declare function groupBy<T, K extends PropertyKey>(items: Iterable<T>, keyFn: (item: T, index: number) => K): Partial<Record<K, T[]>>;
|
|
26
|
+
/**
|
|
27
|
+
* Groups into a `Map` (native `Map.groupBy` when present); keys use SameValueZero.
|
|
28
|
+
* @example
|
|
29
|
+
* groupByToMap([{ d: 1 }, { d: 2 }, { d: 1 }], (x) => x.d).get(1)?.length; // => 2
|
|
30
|
+
*/
|
|
31
|
+
export declare function groupByToMap<T, K>(items: Iterable<T>, keyFn: (item: T, index: number) => K): Map<K, T[]>;
|
|
32
|
+
/**
|
|
33
|
+
* Indexes items by key into a null-prototype record; later items win.
|
|
34
|
+
* @example
|
|
35
|
+
* keyBy([{ id: 'a' }, { id: 'b' }], (x) => x.id); // => { a: { id: 'a' }, b: { id: 'b' } }
|
|
36
|
+
*/
|
|
37
|
+
export declare function keyBy<T, K extends PropertyKey>(items: Iterable<T>, keyFn: (item: T, index: number) => K): Partial<Record<K, T>>;
|
|
38
|
+
/**
|
|
39
|
+
* Counts items per key into a null-prototype record.
|
|
40
|
+
* @example
|
|
41
|
+
* countBy(['a', 'bb', 'cc'], (s) => s.length); // => { 1: 1, 2: 2 }
|
|
42
|
+
*/
|
|
43
|
+
export declare function countBy<T, K extends PropertyKey>(items: Iterable<T>, keyFn: (item: T, index: number) => K): Partial<Record<K, number>>;
|
|
44
|
+
/**
|
|
45
|
+
* Combines arrays element-wise into tuples; stops at the shortest array.
|
|
46
|
+
* @example
|
|
47
|
+
* zip([1, 2, 3], ['a', 'b']); // => [[1, 'a'], [2, 'b']]
|
|
48
|
+
*/
|
|
49
|
+
export declare function zip<const T extends readonly (readonly unknown[])[]>(...arrays: T): {
|
|
50
|
+
-readonly [K in keyof T]: T[K][number];
|
|
51
|
+
}[];
|
|
52
|
+
/**
|
|
53
|
+
* Combines two arrays element-wise with `fn`; stops at the shorter array.
|
|
54
|
+
* @example
|
|
55
|
+
* zipWith([1, 2], [10, 20], (a, b) => a + b); // => [11, 22]
|
|
56
|
+
*/
|
|
57
|
+
export declare function zipWith<A, B, R>(a: readonly A[], b: readonly B[], fn: (a: A, b: B, index: number) => R): R[];
|
|
58
|
+
/**
|
|
59
|
+
* Inverse of `zip`: splits tuples into one array per position (width of the longest row).
|
|
60
|
+
* @example
|
|
61
|
+
* unzip([[1, 'a'], [2, 'b']] as [number, string][]); // => [[1, 2], ['a', 'b']]
|
|
62
|
+
*/
|
|
63
|
+
export declare function unzip<const T extends readonly unknown[]>(rows: readonly T[]): {
|
|
64
|
+
-readonly [K in keyof T]: T[K][];
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Flattens nested arrays up to `depth` (default 1).
|
|
68
|
+
* @example
|
|
69
|
+
* flatten([1, [2, [3]]]); // => [1, 2, [3]]
|
|
70
|
+
*/
|
|
71
|
+
export declare function flatten<A extends readonly unknown[], D extends number = 1>(items: A, depth?: D): FlatArray<A, D>[];
|
|
72
|
+
/**
|
|
73
|
+
* Flattens all nesting levels.
|
|
74
|
+
* @example
|
|
75
|
+
* flattenDeep([1, [2, [3, [4]]]]); // => [1, 2, 3, 4]
|
|
76
|
+
*/
|
|
77
|
+
export declare function flattenDeep<A extends readonly unknown[]>(items: A): FlatArray<A, 20>[];
|
|
78
|
+
/**
|
|
79
|
+
* Removes `null`, `undefined`, and `false` (keeps `0`, `''`, and `NaN`).
|
|
80
|
+
* @example
|
|
81
|
+
* compact([0, null, 'a', false, undefined]); // => [0, 'a']
|
|
82
|
+
*/
|
|
83
|
+
export declare function compact<T>(items: readonly T[]): Exclude<T, null | undefined | false>[];
|
|
84
|
+
/**
|
|
85
|
+
* Removes duplicates (SameValueZero), keeping first occurrences.
|
|
86
|
+
* @example
|
|
87
|
+
* uniq([1, 2, 1, NaN, NaN]); // => [1, 2, NaN]
|
|
88
|
+
*/
|
|
89
|
+
export declare function uniq<T>(items: readonly T[]): T[];
|
|
90
|
+
/**
|
|
91
|
+
* Removes items with a duplicate key, keeping first occurrences.
|
|
92
|
+
* @example
|
|
93
|
+
* uniqBy([{ id: 1 }, { id: 1 }, { id: 2 }], (x) => x.id); // => [{ id: 1 }, { id: 2 }]
|
|
94
|
+
*/
|
|
95
|
+
export declare function uniqBy<T>(items: readonly T[], keyFn: (item: T) => unknown): T[];
|
|
96
|
+
/** One sort key: a selector with direction, null placement, and string ordering. */
|
|
97
|
+
export interface SortKey<T> {
|
|
98
|
+
readonly by: (item: T) => unknown;
|
|
99
|
+
/** Default `'asc'`. */
|
|
100
|
+
readonly order?: 'asc' | 'desc';
|
|
101
|
+
/** Placement of empty keys (nullish, `NaN`, invalid dates), independent of `order`. Default `'last'`. */
|
|
102
|
+
readonly nulls?: 'first' | 'last';
|
|
103
|
+
/** String collation for this key; overrides `SortByOptions.collator`. */
|
|
104
|
+
readonly collator?: Intl.Collator;
|
|
105
|
+
/** Custom comparer for non-empty keys; overrides collation. */
|
|
106
|
+
readonly compare?: Comparer<unknown>;
|
|
107
|
+
}
|
|
108
|
+
export interface SortByOptions {
|
|
109
|
+
/** Collator for string keys. Strings compare by code unit when neither this nor `locale` is set. */
|
|
110
|
+
readonly collator?: Intl.Collator;
|
|
111
|
+
/** Locale for a cached `Intl.Collator` (used when `collator` is absent). */
|
|
112
|
+
readonly locale?: string | readonly string[];
|
|
113
|
+
/** Default null placement for keys without their own. Default `'last'`. */
|
|
114
|
+
readonly nulls?: 'first' | 'last';
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Stable multi-key sort. Keys are evaluated once per item.
|
|
118
|
+
* @example
|
|
119
|
+
* const people = [{ name: 'Ada', dept: 'Vertrieb', salary: 50 }, { name: 'Ben', dept: 'Ärzte', salary: 40 }, { name: 'Cy', dept: 'Vertrieb', salary: 70 }];
|
|
120
|
+
* sortBy(people, [{ by: (p) => p.dept }, { by: (p) => p.salary, order: 'desc' }], { locale: 'de' }).map((p) => p.name); // => ['Ben', 'Cy', 'Ada']
|
|
121
|
+
*/
|
|
122
|
+
export declare function sortBy<T>(items: readonly T[], keys: ((item: T) => unknown) | SortKey<T> | readonly (((item: T) => unknown) | SortKey<T>)[], options?: SortByOptions): T[];
|
|
123
|
+
/**
|
|
124
|
+
* Index of `target` in a sorted array, or `~insertionPoint` (negative) when absent.
|
|
125
|
+
* @example
|
|
126
|
+
* binarySearch([1, 3, 5], 3); // => 1
|
|
127
|
+
* ~binarySearch([1, 3, 5], 4); // => 2
|
|
128
|
+
*/
|
|
129
|
+
export declare function binarySearch<T>(sorted: readonly T[], target: T, compare?: Comparer<T>): number;
|
|
130
|
+
/**
|
|
131
|
+
* First index whose element is not less than `target`.
|
|
132
|
+
* @example
|
|
133
|
+
* lowerBound([1, 2, 2, 3], 2); // => 1
|
|
134
|
+
*/
|
|
135
|
+
export declare function lowerBound<T>(sorted: readonly T[], target: T, compare?: Comparer<T>): number;
|
|
136
|
+
/**
|
|
137
|
+
* First index whose element is greater than `target`.
|
|
138
|
+
* @example
|
|
139
|
+
* upperBound([1, 2, 2, 3], 2); // => 3
|
|
140
|
+
*/
|
|
141
|
+
export declare function upperBound<T>(sorted: readonly T[], target: T, compare?: Comparer<T>): number;
|
|
142
|
+
/**
|
|
143
|
+
* The `n` largest items, largest first (stable for ties). O(len log n).
|
|
144
|
+
* @example
|
|
145
|
+
* topN([5, 1, 9, 3], 2); // => [9, 5]
|
|
146
|
+
* const users = [{ name: 'Ada', score: 7 }, { name: 'Ben', score: 9 }, { name: 'Cy', score: 4 }];
|
|
147
|
+
* topN(users, 2, (a, b) => a.score - b.score).map((u) => u.name); // => ['Ben', 'Ada']
|
|
148
|
+
*/
|
|
149
|
+
export declare function topN<T>(items: readonly T[], n: number, compare?: Comparer<T>): T[];
|
|
150
|
+
/**
|
|
151
|
+
* The `n` smallest items, smallest first (stable for ties). O(len log n).
|
|
152
|
+
* @example
|
|
153
|
+
* bottomN([5, 1, 9, 3], 2); // => [1, 3]
|
|
154
|
+
*/
|
|
155
|
+
export declare function bottomN<T>(items: readonly T[], n: number, compare?: Comparer<T>): T[];
|
|
156
|
+
/**
|
|
157
|
+
* Moves the item at `from` to `to` (negative indexes count from the end).
|
|
158
|
+
* @example
|
|
159
|
+
* move(['a', 'b', 'c'], 0, 2); // => ['b', 'c', 'a']
|
|
160
|
+
*/
|
|
161
|
+
export declare function move<T>(items: readonly T[], from: number, to: number): T[];
|
|
162
|
+
/**
|
|
163
|
+
* Inserts items before `index` (`index === length` appends; negative counts from the end).
|
|
164
|
+
* @example
|
|
165
|
+
* insertAt([1, 4], 1, 2, 3); // => [1, 2, 3, 4]
|
|
166
|
+
*/
|
|
167
|
+
export declare function insertAt<T>(items: readonly T[], index: number, ...values: T[]): T[];
|
|
168
|
+
/**
|
|
169
|
+
* Removes `count` items starting at `index` (negative counts from the end).
|
|
170
|
+
* @example
|
|
171
|
+
* removeAt([1, 2, 3, 4], 1, 2); // => [1, 4]
|
|
172
|
+
*/
|
|
173
|
+
export declare function removeAt<T>(items: readonly T[], index: number, count?: number): T[];
|
|
174
|
+
/**
|
|
175
|
+
* Replaces the item at `index` (negative counts from the end).
|
|
176
|
+
* @example
|
|
177
|
+
* replaceAt([1, 2, 3], -1, 9); // => [1, 2, 9]
|
|
178
|
+
*/
|
|
179
|
+
export declare function replaceAt<T>(items: readonly T[], index: number, value: T): T[];
|
|
180
|
+
/**
|
|
181
|
+
* Swaps two items.
|
|
182
|
+
* @example
|
|
183
|
+
* swap([1, 2, 3], 0, 2); // => [3, 2, 1]
|
|
184
|
+
*/
|
|
185
|
+
export declare function swap<T>(items: readonly T[], i: number, j: number): T[];
|
|
186
|
+
/**
|
|
187
|
+
* Removes every item equal to `item`, or appends it when absent.
|
|
188
|
+
* @example
|
|
189
|
+
* toggleItem([1, 2], 2); // => [1]
|
|
190
|
+
* toggleItem([1, 2], 3); // => [1, 2, 3]
|
|
191
|
+
*/
|
|
192
|
+
export declare function toggleItem<T>(items: readonly T[], item: T, equals?: (a: T, b: T) => boolean): T[];
|
|
193
|
+
/**
|
|
194
|
+
* Replaces the first item with the same key, or appends.
|
|
195
|
+
* @example
|
|
196
|
+
* upsertBy([{ id: 1, v: 'a' }], { id: 1, v: 'b' }, (x) => x.id); // => [{ id: 1, v: 'b' }]
|
|
197
|
+
*/
|
|
198
|
+
export declare function upsertBy<T>(items: readonly T[], item: T, keyFn: (item: T) => unknown): T[];
|
|
199
|
+
/**
|
|
200
|
+
* Rotates by `n` positions: positive moves items toward the end, negative toward the start.
|
|
201
|
+
* @example
|
|
202
|
+
* rotate([1, 2, 3, 4], 1); // => [4, 1, 2, 3]
|
|
203
|
+
* rotate([1, 2, 3, 4], -1); // => [2, 3, 4, 1]
|
|
204
|
+
*/
|
|
205
|
+
export declare function rotate<T>(items: readonly T[], n: number): T[];
|
|
206
|
+
/**
|
|
207
|
+
* Splits into `[before, fromIndex]` (negative counts from the end; out of range clamps).
|
|
208
|
+
* @example
|
|
209
|
+
* splitAt([1, 2, 3], 1); // => [[1], [2, 3]]
|
|
210
|
+
*/
|
|
211
|
+
export declare function splitAt<T>(items: readonly T[], index: number): [T[], T[]];
|
|
212
|
+
/**
|
|
213
|
+
* Inserts `separator` between items.
|
|
214
|
+
* @example
|
|
215
|
+
* intersperse(['a', 'b', 'c'], ','); // => ['a', ',', 'b', ',', 'c']
|
|
216
|
+
*/
|
|
217
|
+
export declare function intersperse<T, S>(items: readonly T[], separator: S): (T | S)[];
|
|
218
|
+
/**
|
|
219
|
+
* Leading items while `predicate` holds.
|
|
220
|
+
* @example
|
|
221
|
+
* takeWhile([1, 2, 5, 1], (n) => n < 3); // => [1, 2]
|
|
222
|
+
*/
|
|
223
|
+
export declare function takeWhile<T>(items: readonly T[], predicate: (item: T, index: number) => boolean): T[];
|
|
224
|
+
/**
|
|
225
|
+
* Items after the leading run where `predicate` holds.
|
|
226
|
+
* @example
|
|
227
|
+
* dropWhile([1, 2, 5, 1], (n) => n < 3); // => [5, 1]
|
|
228
|
+
*/
|
|
229
|
+
export declare function dropWhile<T>(items: readonly T[], predicate: (item: T, index: number) => boolean): T[];
|
|
230
|
+
/**
|
|
231
|
+
* Numbers from `start` (inclusive) to `end` (exclusive) by `step`. `range(n)` is `0..n-1`.
|
|
232
|
+
* Throws `HLP_ARRAY_INVALID_RANGE` for non-finite input or a zero step, and `HLP_ARRAY_TOO_LARGE` above `MAX_GENERATED_LENGTH`.
|
|
233
|
+
* @example
|
|
234
|
+
* range(3); // => [0, 1, 2]
|
|
235
|
+
* range(10, 0, -5); // => [10, 5]
|
|
236
|
+
* range(0, 1, 0.25); // => [0, 0.25, 0.5, 0.75]
|
|
237
|
+
*/
|
|
238
|
+
export declare function range(start: number, end?: number, step?: number): number[];
|
|
239
|
+
/**
|
|
240
|
+
* Calls `fn` `count` times and collects the results.
|
|
241
|
+
* @example
|
|
242
|
+
* times(3, (i) => i * 2); // => [0, 2, 4]
|
|
243
|
+
*/
|
|
244
|
+
export declare function times<T>(count: number, fn: (index: number) => T): T[];
|
|
245
|
+
/**
|
|
246
|
+
* An array of `count` copies of `value`.
|
|
247
|
+
* @example
|
|
248
|
+
* repeat('x', 3); // => ['x', 'x', 'x']
|
|
249
|
+
*/
|
|
250
|
+
export declare function repeat<T>(value: T, count: number): T[];
|
|
251
|
+
/**
|
|
252
|
+
* Sliding windows of `size`, advancing by `step`; only full windows are returned.
|
|
253
|
+
* @example
|
|
254
|
+
* windowed([1, 2, 3, 4], 2); // => [[1, 2], [2, 3], [3, 4]]
|
|
255
|
+
* windowed([1, 2, 3, 4, 5], 2, 2); // => [[1, 2], [3, 4]]
|
|
256
|
+
*/
|
|
257
|
+
export declare function windowed<T>(items: readonly T[], size: number, step?: number): T[][];
|
|
258
|
+
/**
|
|
259
|
+
* Adjacent pairs.
|
|
260
|
+
* @example
|
|
261
|
+
* pairwise([1, 2, 3]); // => [[1, 2], [2, 3]]
|
|
262
|
+
*/
|
|
263
|
+
export declare function pairwise<T>(items: readonly T[]): [T, T][];
|
|
264
|
+
/** One page of a list. */
|
|
265
|
+
export interface Page<T> {
|
|
266
|
+
readonly items: T[];
|
|
267
|
+
readonly total: number;
|
|
268
|
+
/** 1-based page number as requested. */
|
|
269
|
+
readonly page: number;
|
|
270
|
+
readonly pageSize: number;
|
|
271
|
+
readonly pageCount: number;
|
|
272
|
+
readonly hasNext: boolean;
|
|
273
|
+
readonly hasPrev: boolean;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* Slices one 1-based page. Pages past the end have no items.
|
|
277
|
+
* @example
|
|
278
|
+
* paginate(range(25), 3, 10); // => { items: [20, 21, 22, 23, 24], total: 25, page: 3, pageSize: 10, pageCount: 3, hasNext: false, hasPrev: true }
|
|
279
|
+
*/
|
|
280
|
+
export declare function paginate<T>(items: readonly T[], page: number, pageSize: number): Page<T>;
|
|
281
|
+
/**
|
|
282
|
+
* First item, or `undefined`.
|
|
283
|
+
* @example
|
|
284
|
+
* first([1, 2]); // => 1
|
|
285
|
+
*/
|
|
286
|
+
export declare function first<T>(items: readonly T[]): T | undefined;
|
|
287
|
+
/**
|
|
288
|
+
* Last item, or `undefined`.
|
|
289
|
+
* @example
|
|
290
|
+
* last([1, 2]); // => 2
|
|
291
|
+
*/
|
|
292
|
+
export declare function last<T>(items: readonly T[]): T | undefined;
|
|
293
|
+
/**
|
|
294
|
+
* Item at `index` (negative counts from the end), or `undefined`.
|
|
295
|
+
* @example
|
|
296
|
+
* nth([1, 2, 3], -2); // => 2
|
|
297
|
+
*/
|
|
298
|
+
export declare function nth<T>(items: readonly T[], index: number): T | undefined;
|
|
299
|
+
/**
|
|
300
|
+
* Sum of `fn` over items with compensated (Neumaier) summation.
|
|
301
|
+
* @example
|
|
302
|
+
* sumBy([{ n: 1e100 }, { n: 1 }, { n: -1e100 }], (x) => x.n); // => 1 // plain addition gives 0
|
|
303
|
+
*/
|
|
304
|
+
export declare function sumBy<T>(items: readonly T[], fn: (item: T, index: number) => number): number;
|
|
305
|
+
/**
|
|
306
|
+
* Mean of `fn` over items, or `undefined` for an empty array.
|
|
307
|
+
* @example
|
|
308
|
+
* averageBy([{ n: 2 }, { n: 4 }], (x) => x.n); // => 3
|
|
309
|
+
*/
|
|
310
|
+
export declare function averageBy<T>(items: readonly T[], fn: (item: T, index: number) => number): number | undefined;
|
|
311
|
+
/**
|
|
312
|
+
* Item with the smallest key (first on ties; empty keys ignored), or `undefined`.
|
|
313
|
+
* @example
|
|
314
|
+
* minBy([{ n: 2 }, { n: 1 }], (x) => x.n); // => { n: 1 }
|
|
315
|
+
*/
|
|
316
|
+
export declare function minBy<T>(items: readonly T[], fn: (item: T) => unknown): T | undefined;
|
|
317
|
+
/**
|
|
318
|
+
* Item with the largest key (first on ties; empty keys ignored), or `undefined`.
|
|
319
|
+
* @example
|
|
320
|
+
* maxBy([{ n: 2 }, { n: 1 }], (x) => x.n); // => { n: 2 }
|
|
321
|
+
*/
|
|
322
|
+
export declare function maxBy<T>(items: readonly T[], fn: (item: T) => unknown): T | undefined;
|
|
323
|
+
/**
|
|
324
|
+
* Shallow element-wise equality (default `Object.is`).
|
|
325
|
+
* @example
|
|
326
|
+
* arraysEqual([1, 2], [1, 2]); // => true
|
|
327
|
+
*/
|
|
328
|
+
export declare function arraysEqual<T>(a: readonly T[], b: readonly T[], equals?: (x: T, y: T) => boolean): boolean;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.2 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{LimitError as K,ValidationError as N}from"../error/index.js";import{compareNatural as d,isEmptyKey as g}from"./compare.js";import{buildTree as Re,flattenTree as Ke}from"./tree.js";const A=1e7,c=(e,n)=>new N(e,n);function m(e,n,t){if(!Number.isSafeInteger(e)||e<1)throw c(n,t)}function I(e){if(e>A)throw new K("HLP_ARRAY_TOO_LARGE","The requested array length exceeds the limit.",{details:{limit:A}})}function w(e,n){if(!Number.isInteger(n))return;const t=n<0?e+n:n;return t>=0&&t<e?t:void 0}function p(e,n){const t=w(e,n);if(t===void 0)throw c("HLP_ARRAY_INDEX_OUT_OF_RANGE","The index is out of range.");return t}function E(e,n){m(n,"HLP_ARRAY_INVALID_SIZE","Chunk size must be a positive integer.");const t=[];for(let r=0;r<e.length;r+=n)t.push(e.slice(r,r+n));return t}function C(e,n){const t=[],r=[];return e.forEach((o,u)=>(n(o,u)?t:r).push(o)),[t,r]}function S(e,n){const t=Object.groupBy;if(typeof t=="function")return t(e,n);const r=Object.create(null);let o=0;for(const u of e){const a=n(u,o++),i=r[a];i?i.push(u):r[a]=[u]}return r}function D(e,n){const t=Map.groupBy;if(typeof t=="function")return t(e,n);const r=new Map;let o=0;for(const u of e){const a=n(u,o++),i=r.get(a);i?i.push(u):r.set(a,[u])}return r}function O(e,n){const t=Object.create(null);let r=0;for(const o of e)t[n(o,r++)]=o;return t}function M(e,n){const t=Object.create(null);let r=0;for(const o of e){const u=n(o,r++);t[u]=(t[u]??0)+1}return t}function H(...e){if(e.length===0)return[];const n=Math.min(...e.map(r=>r.length)),t=[];for(let r=0;r<n;r++)t.push(e.map(o=>o[r]));return t}function V(e,n,t){const r=Math.min(e.length,n.length),o=[];for(let u=0;u<r;u++)o.push(t(e[u],n[u],u));return o}function Y(e){const n=e.reduce((r,o)=>Math.max(r,o.length),0),t=Array.from({length:n},()=>[]);for(const r of e)for(let o=0;o<n;o++)t[o]?.push(r[o]);return t}function j(e,n){const t=n??1;if(!(t===1/0||Number.isInteger(t)&&t>=0))throw c("HLP_ARRAY_INVALID_DEPTH","Depth must be a non-negative integer.");return e.flat(t)}function G(e){return e.flat(1/0)}function F(e){return e.filter(n=>n!=null&&n!==!1)}function q(e){return[...new Set(e)]}function U(e,n){const t=new Set,r=[];for(const o of e){const u=n(o);t.has(u)||(t.add(u),r.push(o))}return r}const x=new Map;function P(e){const n=typeof e=="string"?e:e.join(",");let t=x.get(n);return t||(x.size>=32&&x.clear(),t=new Intl.Collator(typeof e=="string"?e:[...e]),x.set(n,t)),t}function W(e,n,t={}){const r=Array.isArray(n)?n:[n],o=t.collator??(t.locale===void 0?void 0:P(t.locale)),u=r.map(i=>{const l=typeof i=="function"?{by:i}:i,s=l.order==="desc"?-1:1,T=(l.nulls??t.nulls??"last")==="first",f=l.collator??o,y=l.compare,b=e.map(h=>l.by(h));return{dir:s,nullsFirst:T,collator:f,cmp:y,values:b}}),a=e.map((i,l)=>l);return a.sort((i,l)=>{for(const s of u){const T=s.values[i],f=s.values[l],y=g(T),b=g(f);if(y||b){if(y&&b)continue;return y===s.nullsFirst?-1:1}const h=s.cmp?s.cmp(T,f):d(T,f,s.collator);if(h!==0)return h*s.dir}return i-l}),a.map(i=>e[i])}function Z(e,n,t=d){let r=0,o=e.length-1;for(;r<=o;){const u=r+o>>>1,a=t(e[u],n);if(a===0)return u;a<0?r=u+1:o=u-1}return~r}function X(e,n,t=d){let r=0,o=e.length;for(;r<o;){const u=r+o>>>1;t(e[u],n)<0?r=u+1:o=u}return r}function z(e,n,t=d){let r=0,o=e.length;for(;r<o;){const u=r+o>>>1;t(e[u],n)<=0?r=u+1:o=u}return r}function _(e,n,t){if(!Number.isSafeInteger(n)||n<0)throw c("HLP_ARRAY_INVALID_COUNT","Count must be a non-negative integer.");if(n===0)return[];const r=(i,l)=>{const s=t(e[i],e[l]);return s<0||s===0&&i<l},o=[],u=i=>o[i]??0,a=i=>{for(;;){const l=2*i+1,s=l+1;let T=i;if(l<o.length&&r(u(T),u(l))&&(T=l),s<o.length&&r(u(T),u(s))&&(T=s),T===i)return;const f=u(T);o[T]=u(i),o[i]=f,i=T}};for(let i=0;i<e.length;i++)if(o.length<n){let l=o.push(i)-1;for(;l>0;){const s=l-1>>1;if(!r(u(s),u(l)))break;const T=u(s);o[s]=u(l),o[l]=T,l=s}}else r(i,u(0))&&(o[0]=i,a(0));return o.sort((i,l)=>r(i,l)?-1:1).map(i=>e[i])}function J(e,n,t=d){return _(e,n,(r,o)=>t(o,r))}function Q(e,n,t=d){return _(e,n,t)}function $(e,n,t){const r=p(e.length,n),o=p(e.length,t),u=e.slice(),[a]=u.splice(r,1);return u.splice(o,0,a),u}function ee(e,n,...t){const r=n===e.length?n:p(e.length,n);return[...e.slice(0,r),...t,...e.slice(r)]}function ne(e,n,t=1){const r=p(e.length,n);if(!Number.isSafeInteger(t)||t<0)throw c("HLP_ARRAY_INVALID_COUNT","Count must be a non-negative integer.");return e.toSpliced(r,t)}function te(e,n,t){return e.with(p(e.length,n),t)}function re(e,n,t){const r=p(e.length,n),o=p(e.length,t),u=e.slice();return[u[r],u[o]]=[e[o],e[r]],u}function oe(e,n,t=Object.is){const r=e.filter(o=>!t(o,n));return r.length===e.length?[...e,n]:r}function ue(e,n,t){const r=t(n),o=e.findIndex(u=>Object.is(t(u),r));return o<0?[...e,n]:e.with(o,n)}function ie(e,n){const t=e.length;if(!Number.isInteger(n))throw c("HLP_ARRAY_INVALID_COUNT","Rotation must be an integer.");if(t===0)return[];const r=(-n%t+t)%t;return[...e.slice(r),...e.slice(0,r)]}function le(e,n){return[e.slice(0,n),e.slice(n)]}function ae(e,n){const t=[];return e.forEach((r,o)=>{o>0&&t.push(n),t.push(r)}),t}function se(e,n){const t=e.findIndex((r,o)=>!n(r,o));return t<0?e.slice():e.slice(0,t)}function Te(e,n){const t=e.findIndex((r,o)=>!n(r,o));return t<0?[]:e.slice(t)}function ce(e,n,t){const[r,o]=n===void 0?[0,e]:[e,n],u=t??(o>=r?1:-1);if(!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(u)||u===0)throw c("HLP_ARRAY_INVALID_RANGE","Range bounds and step must be finite and the step non-zero.");const a=Math.max(0,Math.ceil((o-r)/u));return I(a),Array.from({length:a},(i,l)=>r+l*u)}function B(e,n){if(!Number.isSafeInteger(e)||e<0)throw c("HLP_ARRAY_INVALID_COUNT","Count must be a non-negative integer.");return I(e),Array.from({length:e},(t,r)=>n(r))}function fe(e,n){return B(n,()=>e)}function de(e,n,t=1){m(n,"HLP_ARRAY_INVALID_SIZE","Window size must be a positive integer."),m(t,"HLP_ARRAY_INVALID_SIZE","Window step must be a positive integer.");const r=[];for(let o=0;o+n<=e.length;o+=t)r.push(e.slice(o,o+n));return r}function pe(e){const n=[];for(let t=1;t<e.length;t++)n.push([e[t-1],e[t]]);return n}function ye(e,n,t){m(n,"HLP_ARRAY_INVALID_PAGE","Page must be a positive integer."),m(t,"HLP_ARRAY_INVALID_PAGE","Page size must be a positive integer.");const r=e.length,o=Math.ceil(r/t),u=(n-1)*t;return{items:e.slice(u,u+t),total:r,page:n,pageSize:t,pageCount:o,hasNext:n<o,hasPrev:n>1}}function me(e){return e[0]}function be(e){return e[e.length-1]}function he(e,n){const t=w(e.length,n);return t===void 0?void 0:e[t]}function k(e,n){let t=0,r=0;return e.forEach((o,u)=>{const a=n(o,u),i=t+a;r+=Math.abs(t)>=Math.abs(a)?t-i+a:a-i+t,t=i}),t+r}function xe(e,n){return e.length===0?void 0:k(e,n)/e.length}function R(e,n,t){let r,o,u=!1;for(const a of e){const i=n(a);g(i)||(!u||d(i,o)*t<0)&&(r=a,o=i,u=!0)}return r}function ge(e,n){return R(e,n,1)}function Ae(e,n){return R(e,n,-1)}function Ie(e,n,t=Object.is){if(e===n)return!0;if(e.length!==n.length)return!1;for(let r=0;r<e.length;r++)if(!t(e[r],n[r]))return!1;return!0}export{A as MAX_GENERATED_LENGTH,Ie as arraysEqual,xe as averageBy,Z as binarySearch,Q as bottomN,Re as buildTree,E as chunk,F as compact,M as countBy,Te as dropWhile,me as first,j as flatten,G as flattenDeep,Ke as flattenTree,S as groupBy,D as groupByToMap,ee as insertAt,ae as intersperse,O as keyBy,be as last,X as lowerBound,Ae as maxBy,ge as minBy,$ as move,he as nth,ye as paginate,pe as pairwise,C as partition,ce as range,ne as removeAt,fe as repeat,te as replaceAt,ie as rotate,W as sortBy,le as splitAt,k as sumBy,re as swap,se as takeWhile,B as times,oe as toggleItem,J as topN,q as uniq,U as uniqBy,Y as unzip,z as upperBound,ue as upsertBy,de as windowed,H as zip,V as zipWith};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/** A tree node wrapping the original item. */
|
|
2
|
+
export interface TreeNode<T> {
|
|
3
|
+
readonly item: T;
|
|
4
|
+
readonly children: TreeNode<T>[];
|
|
5
|
+
}
|
|
6
|
+
/** Field name or selector. */
|
|
7
|
+
type KeySpec<T> = keyof T | ((item: T) => unknown);
|
|
8
|
+
export interface BuildTreeOptions<T> {
|
|
9
|
+
/** Id field or selector. Default `'id'`. */
|
|
10
|
+
readonly id?: KeySpec<T>;
|
|
11
|
+
/** Parent-id field or selector; nullish means root. Default `'parentId'`. */
|
|
12
|
+
readonly parentId?: KeySpec<T>;
|
|
13
|
+
/** Items whose parent is missing: `'root'` (default) promotes them to roots, `'omit'` leaves them out. */
|
|
14
|
+
readonly orphans?: 'root' | 'omit';
|
|
15
|
+
}
|
|
16
|
+
export interface BuildTreeResult<T> {
|
|
17
|
+
readonly roots: TreeNode<T>[];
|
|
18
|
+
/** Items whose parent id matched no item. */
|
|
19
|
+
readonly orphans: T[];
|
|
20
|
+
/** Items unreachable from any root because their ancestry loops (including their descendants). */
|
|
21
|
+
readonly cycles: T[];
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Builds a tree from `id`/`parentId` records in input order. Throws `HLP_ARRAY_DUPLICATE_ID` on repeated ids.
|
|
25
|
+
* @example
|
|
26
|
+
* const { roots } = buildTree([{ id: 1, parentId: null }, { id: 2, parentId: 1 }]);
|
|
27
|
+
* roots[0]?.children[0]?.item.id; // => 2
|
|
28
|
+
*/
|
|
29
|
+
export declare function buildTree<T extends object>(items: readonly T[], options?: BuildTreeOptions<T>): BuildTreeResult<T>;
|
|
30
|
+
export interface FlattenTreeOptions<N> {
|
|
31
|
+
/** Child accessor. Default reads a `children` array property. */
|
|
32
|
+
readonly children?: (node: N) => Iterable<N> | null | undefined;
|
|
33
|
+
/** `'depth'` (pre-order, default) or `'breadth'`. */
|
|
34
|
+
readonly order?: 'depth' | 'breadth';
|
|
35
|
+
}
|
|
36
|
+
export interface FlatTreeEntry<N> {
|
|
37
|
+
readonly node: N;
|
|
38
|
+
readonly depth: number;
|
|
39
|
+
readonly parent: N | undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Flattens a tree into entries with depth and parent. Throws `HLP_ARRAY_TREE_CYCLE` when a node is reached twice.
|
|
43
|
+
* @example
|
|
44
|
+
* const rows = [{ id: 1, parentId: null, name: 'CEO' }, { id: 2, parentId: 1, name: 'CTO' }, { id: 3, parentId: 1, name: 'CFO' }];
|
|
45
|
+
* flattenTree(buildTree(rows).roots).map((e) => `${' '.repeat(e.depth)}${e.node.item.name}`); // => ['CEO', ' CTO', ' CFO']
|
|
46
|
+
*/
|
|
47
|
+
export declare function flattenTree<N>(roots: Iterable<N>, options?: FlattenTreeOptions<N>): FlatTreeEntry<N>[];
|
|
48
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.2 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{ValidationError as f}from"../error/index.js";function h(t){return typeof t=="function"?t:r=>r[t]}function w(t,r={}){const u=h(r.id??"id"),l=h(r.parentId??"parentId"),c=new Map,p=t.map(n=>{const o={item:n,children:[]},T=u(n);if(c.has(T))throw new f("HLP_ARRAY_DUPLICATE_ID","Tree items must have unique ids.");return c.set(T,o),o}),d=[],a=[],e=[];for(const n of p){const o=l(n.item);if(o==null){d.push(n),a.push(n);continue}const T=c.get(o);T?T.children.push(n):(e.push(n.item),a.push(n),r.orphans!=="omit"&&d.push(n))}const s=new Set,i=[...a];for(let n=i.pop();n;n=i.pop()){s.add(n);for(const o of n.children)i.push(o)}const y=p.filter(n=>!s.has(n)).map(n=>n.item);return{roots:d,orphans:e,cycles:y}}function N(t){const r=typeof t=="object"&&t!==null?t.children:void 0;return Array.isArray(r)?r:void 0}function k(t,r={}){const u=r.children??N,l=[],c=new Set,p=e=>{if(c.has(e.node))throw new f("HLP_ARRAY_TREE_CYCLE","The tree contains a cycle or a shared node.");return c.add(e.node),l.push(e),[...u(e.node)??[]]},d=[...t].map(e=>({node:e,depth:0,parent:void 0}));if(r.order==="breadth"){for(const e of d)for(const s of p(e))d.push({node:s,depth:e.depth+1,parent:e.node});return l}const a=d.reverse();for(let e=a.pop();e;e=a.pop()){const s=p(e);for(let i=s.length-1;i>=0;i--)a.push({node:s[i],depth:e.depth+1,parent:e.node})}return l}export{w as buildTree,k as flattenTree};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { type SignalOptions } from './signal.js';
|
|
2
|
+
export interface BatcherOptions<K> {
|
|
3
|
+
/** Keys per `loadMany` call. Default 100. */
|
|
4
|
+
readonly maxBatchSize?: number;
|
|
5
|
+
/** Ms to collect keys before dispatching. Default 0 (end of the current microtask queue). */
|
|
6
|
+
readonly delay?: number;
|
|
7
|
+
/** Maps a key to its identity for de-duplication within a batch. Default: the key itself (SameValueZero). */
|
|
8
|
+
readonly cacheKey?: (key: K) => unknown;
|
|
9
|
+
}
|
|
10
|
+
/** Batching loader returned by `createBatcher`. */
|
|
11
|
+
export interface Batcher<K, V> {
|
|
12
|
+
/** Loads one key; concurrent calls are coalesced into one `loadMany`. */
|
|
13
|
+
load(key: K): Promise<V>;
|
|
14
|
+
/** Loads several keys (each may land in the same or different batches). */
|
|
15
|
+
loadMany(keys: readonly K[]): Promise<V[]>;
|
|
16
|
+
/** Dispatches the pending batch now. */
|
|
17
|
+
flush(): void;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* DataLoader-style batching: collects `load(key)` calls and resolves them from one `loadMany(keys)` call.
|
|
21
|
+
* `loadMany` must return one result per key in the same order; an `Error` element rejects just that key.
|
|
22
|
+
* No caching across batches (combine with `memoize` or a cache if needed).
|
|
23
|
+
* @example
|
|
24
|
+
* const requests: string[][] = [];
|
|
25
|
+
* const users = createBatcher((ids: string[]) => {
|
|
26
|
+
* requests.push(ids);
|
|
27
|
+
* return ids.map((id) => ({ id, name: `Employee ${id}` }));
|
|
28
|
+
* });
|
|
29
|
+
* const [a, b] = await Promise.all([users.load('1'), users.load('2')]);
|
|
30
|
+
* b; // => { id: '2', name: 'Employee 2' }
|
|
31
|
+
* requests; // => [['1', '2']] // one request for both keys
|
|
32
|
+
*/
|
|
33
|
+
export declare function createBatcher<K, V>(loadMany: (keys: K[]) => PromiseLike<readonly (V | Error)[]> | readonly (V | Error)[], options?: BatcherOptions<K>): Batcher<K, V>;
|
|
34
|
+
/**
|
|
35
|
+
* De-duplicates concurrent calls: while a call for a key is in flight, callers with the same key share its promise.
|
|
36
|
+
* @example
|
|
37
|
+
* let fetches = 0;
|
|
38
|
+
* const getConfig = singleFlight(async (env: string) => {
|
|
39
|
+
* fetches++;
|
|
40
|
+
* return { env, currency: 'EUR' };
|
|
41
|
+
* });
|
|
42
|
+
* await Promise.all([getConfig('prod'), getConfig('prod')]);
|
|
43
|
+
* fetches; // => 1
|
|
44
|
+
*/
|
|
45
|
+
export declare function singleFlight<A extends unknown[], R>(fn: (...args: A) => PromiseLike<R> | R, keyFn?: (...args: A) => unknown): (...args: A) => Promise<R>;
|
|
46
|
+
/** A debounced async function. */
|
|
47
|
+
export interface DebouncedAsync<A extends unknown[], R> {
|
|
48
|
+
(...args: A): Promise<R>;
|
|
49
|
+
/** Drops the scheduled call and rejects every waiting caller with `AbortError`. */
|
|
50
|
+
cancel(): void;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Debounces an async function so only the latest arguments are executed. Choice: every caller whose call
|
|
54
|
+
* was superseded receives the result of the latest call (not an `AbortError`), so all awaiting UI settles on
|
|
55
|
+
* fresh data; results of runs superseded while in flight are discarded. `cancel()` rejects waiters with `AbortError`.
|
|
56
|
+
* @example
|
|
57
|
+
* const search = debounceAsync(async (q: string) => [`${q}: 3 matches`], 20);
|
|
58
|
+
* const [first, latest] = await Promise.all([search('ad'), search('ada')]);
|
|
59
|
+
* first; // => ['ada: 3 matches'] // superseded callers get the latest result
|
|
60
|
+
* latest; // => ['ada: 3 matches']
|
|
61
|
+
*/
|
|
62
|
+
export declare function debounceAsync<A extends unknown[], R>(fn: (...args: A) => PromiseLike<R> | R, wait: number): DebouncedAsync<A, R>;
|
|
63
|
+
type Awaitable<T> = T | PromiseLike<T>;
|
|
64
|
+
/**
|
|
65
|
+
* Async left-to-right composition; each step may return a promise.
|
|
66
|
+
* @example
|
|
67
|
+
* const employees = new Map([['u1', { name: 'Ada', deptId: 'd7' }]]);
|
|
68
|
+
* const departmentOf = asyncPipe(
|
|
69
|
+
* async (id: string) => employees.get(id),
|
|
70
|
+
* (e) => e?.deptId ?? 'unassigned',
|
|
71
|
+
* async (deptId) => `Department ${deptId}`,
|
|
72
|
+
* );
|
|
73
|
+
* await departmentOf('u1'); // => 'Department d7'
|
|
74
|
+
*/
|
|
75
|
+
export declare function asyncPipe<A extends unknown[], B>(ab: (...a: A) => Awaitable<B>): (...a: A) => Promise<B>;
|
|
76
|
+
export declare function asyncPipe<A extends unknown[], B, C>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>): (...a: A) => Promise<C>;
|
|
77
|
+
export declare function asyncPipe<A extends unknown[], B, C, D>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>, cd: (c: C) => Awaitable<D>): (...a: A) => Promise<D>;
|
|
78
|
+
export declare function asyncPipe<A extends unknown[], B, C, D, E>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>, cd: (c: C) => Awaitable<D>, de: (d: D) => Awaitable<E>): (...a: A) => Promise<E>;
|
|
79
|
+
export declare function asyncPipe<A extends unknown[], B, C, D, E, F>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>, cd: (c: C) => Awaitable<D>, de: (d: D) => Awaitable<E>, ef: (e: E) => Awaitable<F>): (...a: A) => Promise<F>;
|
|
80
|
+
export declare function asyncPipe<A extends unknown[], B, C, D, E, F, G>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>, cd: (c: C) => Awaitable<D>, de: (d: D) => Awaitable<E>, ef: (e: E) => Awaitable<F>, fg: (f: F) => Awaitable<G>): (...a: A) => Promise<G>;
|
|
81
|
+
export declare function asyncPipe<A extends unknown[], B, C, D, E, F, G, H>(ab: (...a: A) => Awaitable<B>, bc: (b: B) => Awaitable<C>, cd: (c: C) => Awaitable<D>, de: (d: D) => Awaitable<E>, ef: (e: E) => Awaitable<F>, fg: (f: F) => Awaitable<G>, gh: (g: G) => Awaitable<H>): (...a: A) => Promise<H>;
|
|
82
|
+
/**
|
|
83
|
+
* Wraps a sync iterable (of values or promises) or an async iterable as an async iterable.
|
|
84
|
+
* @example
|
|
85
|
+
* const names: string[] = [];
|
|
86
|
+
* for await (const name of toAsyncIterable([Promise.resolve('Ada'), 'Grace'])) names.push(name);
|
|
87
|
+
* names; // => ['Ada', 'Grace']
|
|
88
|
+
*/
|
|
89
|
+
export declare function toAsyncIterable<T>(source: Iterable<T | PromiseLike<T>> | AsyncIterable<T>): AsyncGenerator<T>;
|
|
90
|
+
export interface CollectOptions extends SignalOptions {
|
|
91
|
+
/** Stop after this many items (the source's `return()` is called). Default: no limit. */
|
|
92
|
+
readonly limit?: number;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Collects an async (or sync) iterable into an array, optionally capped at `limit` items.
|
|
96
|
+
* @example
|
|
97
|
+
* async function* rows() {
|
|
98
|
+
* for (let i = 1; i <= 1_000; i++) yield i;
|
|
99
|
+
* }
|
|
100
|
+
* await collectAsync(rows(), { limit: 3 }); // => [1, 2, 3]
|
|
101
|
+
*/
|
|
102
|
+
export declare function collectAsync<T>(source: AsyncIterable<T> | Iterable<T>, options?: CollectOptions): Promise<T[]>;
|
|
103
|
+
export {};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.2 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{AbortError as P,HelperError as x,ValidationError as p,toError as y}from"../error/index.js";import{assertDelay as k,deferred as h,throwIfAborted as g}from"./signal.js";function D(l,s={}){const e=s.maxBatchSize??100;if(!Number.isSafeInteger(e)||e<1)throw new p("HLP_ASYNC_INVALID_BATCH_SIZE","maxBatchSize must be a positive integer.");const a=s.delay??0;k(a,"delay");const r=s.cacheKey??(c=>c);let n,i;const w=()=>{const c=n;if(n=void 0,i!==void 0&&clearTimeout(i),i=void 0,!c||c.size===0)return;const f=[...c.values()],u=o=>{for(const t of f)for(const d of t.waiters)d.reject(y(o))};Promise.resolve().then(()=>l(f.map(o=>o.key))).then(o=>{if(o.length!==f.length){u(new x("HLP_ASYNC_BATCH_LENGTH","The batch loader returned a different number of results than keys.",{details:{expected:f.length,actual:o.length}}));return}f.forEach((t,d)=>{const A=o[d];for(const m of t.waiters)A instanceof Error?m.reject(A):m.resolve(A)})},u)},b=c=>{n??=new Map;const f=r(c);let u=n.get(f);u||(u={key:c,waiters:[]},n.set(f,u));const o=h();if(u.waiters.push(o),n.size>=e)w();else if(i===void 0&&n.size===1&&u.waiters.length===1)if(a===0){const t=n;queueMicrotask(()=>{n===t&&w()})}else i=setTimeout(w,a);return o.promise};return{load:b,loadMany:c=>Promise.all(c.map(b)),flush:w}}function R(l,s=(...e)=>e[0]){const e=new Map;return(...a)=>{const r=s(...a),n=e.get(r);if(n)return n;const i=Promise.resolve().then(()=>l(...a)).finally(()=>{e.get(r)===i&&e.delete(r)});return e.set(r,i),i}}function C(l,s){k(s,"wait");let e,a,r=0,n=[],i=[];const w=new Set;let b;const c=(o,t)=>{for(const d of o)t.ok?d.resolve(t.value):d.reject(y(t.error))},f=()=>{e=void 0;const o=a,t=n;n=[];const d=r;o&&(w.add(t),Promise.resolve().then(()=>l(...o)).then(A=>({ok:!0,value:A}),A=>({ok:!1,error:A})).then(A=>{w.delete(t)&&(d===r?(b={gen:d,outcome:A},c([...t,...i],A),i=[]):b?.gen===r?c(t,b.outcome):i.push(...t))}))},u=(...o)=>{a=o,r++;const t=h();return n.push(t),e!==void 0&&clearTimeout(e),e=setTimeout(f,s),t.promise};return u.cancel=()=>{e!==void 0&&clearTimeout(e),e=void 0,r++;const o=new P,t=[...n,...i,...[...w].flat()];n=[],i=[],w.clear();for(const d of t)d.reject(o)},u}function E(l,...s){return async(...e)=>{let a=await l(...e);for(const r of s)a=await r(a);return a}}async function*v(l){for await(const s of l)yield s}async function I(l,s={}){const{limit:e=1/0,signal:a}=s;if(!(e>=0))throw new p("HLP_ASYNC_INVALID_LIMIT","limit must be a non-negative number.");const r=[];if(g(a),e===0)return r;for await(const n of l)if(g(a),r.push(n),r.length>=e)break;return r}export{E as asyncPipe,I as collectAsync,D as createBatcher,C as debounceAsync,R as singleFlight,v as toAsyncIterable};
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import { type SignalOptions } from './signal.js';
|
|
2
|
+
export interface MapLimitOptions extends SignalOptions {
|
|
3
|
+
/**
|
|
4
|
+
* `true` (default): the first failure aborts the shared signal, stops scheduling, and rejects with that error.
|
|
5
|
+
* `false`: every item runs; if any failed, rejects with `HLP_ASYNC_MAP_FAILED` whose `cause` is an
|
|
6
|
+
* `AggregateError` of the failures (use `mapLimitSettled` to keep partial results).
|
|
7
|
+
*/
|
|
8
|
+
readonly stopOnError?: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Maps `items` through async `fn` with at most `limit` calls in flight, preserving input order.
|
|
12
|
+
* Items are pulled lazily from the iterable. `fn` receives a signal that aborts on outer abort or first failure.
|
|
13
|
+
* @example
|
|
14
|
+
* const ids = [3, 1, 2];
|
|
15
|
+
* await mapLimit(ids, 2, async (id) => `EMP-${id}`); // => ['EMP-3', 'EMP-1', 'EMP-2']
|
|
16
|
+
*/
|
|
17
|
+
export declare function mapLimit<T, R>(items: Iterable<T>, limit: number, fn: (item: T, index: number, signal: AbortSignal) => PromiseLike<R> | R, options?: MapLimitOptions): Promise<R[]>;
|
|
18
|
+
/**
|
|
19
|
+
* Like `mapLimit` but never rejects for item failures: resolves with a settled result per item, in order.
|
|
20
|
+
* Still rejects with `AbortError` when `signal` aborts.
|
|
21
|
+
* @example
|
|
22
|
+
* const files = ['staff.csv', 'photo.png'];
|
|
23
|
+
* const results = await mapLimitSettled(files, 3, async (f) => {
|
|
24
|
+
* if (!f.endsWith('.csv')) throw new Error('Only CSV files can be imported.');
|
|
25
|
+
* return f;
|
|
26
|
+
* });
|
|
27
|
+
* const { fulfilled, rejected } = partitionSettled(results);
|
|
28
|
+
* fulfilled; // => ['staff.csv']
|
|
29
|
+
* rejected.length; // => 1
|
|
30
|
+
*/
|
|
31
|
+
export declare function mapLimitSettled<T, R>(items: Iterable<T>, limit: number, fn: (item: T, index: number, signal: AbortSignal) => PromiseLike<R> | R, options?: SignalOptions): Promise<PromiseSettledResult<R>[]>;
|
|
32
|
+
/**
|
|
33
|
+
* Splits `Promise.allSettled` output into values and reasons, keeping order within each.
|
|
34
|
+
* @example
|
|
35
|
+
* const results = await Promise.allSettled([Promise.resolve(1), Promise.reject(new Error('Failed.')), Promise.resolve(3)]);
|
|
36
|
+
* partitionSettled(results).fulfilled; // => [1, 3]
|
|
37
|
+
*/
|
|
38
|
+
export declare function partitionSettled<T>(results: readonly PromiseSettledResult<T>[]): {
|
|
39
|
+
fulfilled: T[];
|
|
40
|
+
rejected: unknown[];
|
|
41
|
+
};
|
|
42
|
+
/** Concurrency limiter returned by `createLimiter`. */
|
|
43
|
+
export interface Limiter {
|
|
44
|
+
/** Queues `fn`; it starts when a slot is free. A queued task whose `signal` aborts is dropped and rejects. */
|
|
45
|
+
schedule<T>(fn: (signal: AbortSignal) => PromiseLike<T> | T, options?: SignalOptions): Promise<T>;
|
|
46
|
+
/** Tasks running now. */
|
|
47
|
+
readonly active: number;
|
|
48
|
+
/** Tasks waiting for a slot. */
|
|
49
|
+
readonly pending: number;
|
|
50
|
+
/** Maximum concurrent tasks. */
|
|
51
|
+
readonly concurrency: number;
|
|
52
|
+
/** Resolves when nothing is running or queued. */
|
|
53
|
+
onIdle(): Promise<void>;
|
|
54
|
+
/** Rejects every queued (not yet running) task with `AbortError`. */
|
|
55
|
+
clear(): void;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Runs scheduled async tasks with at most `concurrency` in flight (FIFO). O(1) per schedule/start/cancel.
|
|
59
|
+
* @example
|
|
60
|
+
* const limiter = createLimiter(2);
|
|
61
|
+
* let peak = 0;
|
|
62
|
+
* const task = async (): Promise<void> => {
|
|
63
|
+
* peak = Math.max(peak, limiter.active);
|
|
64
|
+
* await sleep(5);
|
|
65
|
+
* };
|
|
66
|
+
* await Promise.all([1, 2, 3, 4].map(() => limiter.schedule(task)));
|
|
67
|
+
* peak; // => 2
|
|
68
|
+
*/
|
|
69
|
+
export declare function createLimiter(concurrency: number): Limiter;
|
|
70
|
+
/**
|
|
71
|
+
* Runs async tasks one at a time in submission order (a limiter with concurrency 1).
|
|
72
|
+
* @example
|
|
73
|
+
* const writes = createSerialQueue();
|
|
74
|
+
* const saved: string[] = [];
|
|
75
|
+
* const save = async (id: string): Promise<void> => {
|
|
76
|
+
* await sleep(id === 'a' ? 10 : 0);
|
|
77
|
+
* saved.push(id);
|
|
78
|
+
* };
|
|
79
|
+
* await Promise.all([writes.schedule(() => save('a')), writes.schedule(() => save('b'))]);
|
|
80
|
+
* saved; // => ['a', 'b'] // b starts after a finishes
|
|
81
|
+
*/
|
|
82
|
+
export declare function createSerialQueue(): Limiter;
|
|
83
|
+
/**
|
|
84
|
+
* Calls `fn` for each item sequentially, awaiting each call (works with sync and async iterables).
|
|
85
|
+
* @example
|
|
86
|
+
* const applied: string[] = [];
|
|
87
|
+
* await forEachAsync(['001_create', '002_seed'], async (name, i) => {
|
|
88
|
+
* applied.push(`${i}:${name}`);
|
|
89
|
+
* });
|
|
90
|
+
* applied; // => ['0:001_create', '1:002_seed']
|
|
91
|
+
*/
|
|
92
|
+
export declare function forEachAsync<T>(items: Iterable<T> | AsyncIterable<T>, fn: (item: T, index: number, signal: AbortSignal | undefined) => unknown, options?: SignalOptions): Promise<void>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! AbsoluteUI @absoluteui/helpers v0.13.2 | (c) Kasadara Technology Solutions Pvt Ltd | Apache-2.0 | https://aui.kasadara.com/license/ */
|
|
2
|
+
import{AbortError as k,HelperError as E,ValidationError as x,toError as I}from"../error/index.js";import{LinkedList as y}from"../ds/index.js";import{abortReason as L,throwIfAborted as h}from"./signal.js";function w(n){if(!(Number.isSafeInteger(n)&&n>=1)&&n!==1/0)throw new x("HLP_ASYNC_INVALID_LIMIT","Concurrency limit must be a positive integer.")}const O=()=>new AbortController().signal;function H(n,t,r,e={}){const l=e.stopOnError??!0;return A(n,t,r,e.signal,l).then(a=>{const o=[],u=[];for(const i of a)i.status==="fulfilled"?u.push(i.value):o.push(i.reason);if(o.length>0)throw new E("HLP_ASYNC_MAP_FAILED","One or more operations failed.",{cause:new AggregateError(o),details:{failed:o.length,total:a.length}});return u})}function M(n,t,r,e={}){return A(n,t,r,e.signal,!1)}function A(n,t,r,e,l){return new Promise((a,o)=>{if(w(t),e?.aborted){o(L(e));return}const u=new AbortController,i=[],p=n[Symbol.iterator]();let b=0,s=0,d=!1,f=!1;const v=()=>{f=!0,e?.removeEventListener("abort",P)},g=c=>{f||(v(),u.abort(c),d||p.return?.(),o(I(c)))},P=()=>{e&&g(L(e))};e?.addEventListener("abort",P,{once:!0});const S=()=>{for(;!f&&!d&&s<t;){let c;try{c=p.next()}catch(m){g(m);return}if(c.done){d=!0;break}const T=b++,R=c.value;s++,Promise.resolve().then(()=>r(R,T,u.signal)).then(m=>{i[T]={status:"fulfilled",value:m}},m=>{i[T]={status:"rejected",reason:m},l&&g(m)}).finally(()=>{s--,S()})}!f&&d&&s===0&&(v(),a(i))};S()})}function D(n){const t=[],r=[];for(const e of n)e.status==="fulfilled"?t.push(e.value):r.push(e.reason);return{fulfilled:t,rejected:r}}function _(n){w(n);const t=new y;let r=0,e=[];const l=()=>{if(r===0&&t.size===0&&e.length>0){const o=e;e=[];for(const u of o)u()}},a=()=>{for(;r<n&&t.size>0;)t.shift()?.start();l()};return{schedule(o,u={}){const{signal:i}=u;return new Promise((p,b)=>{h(i);let s;const d=()=>{s&&i&&(t.remove(s),s=void 0,b(L(i)),l())},f={start:()=>{s=void 0,i?.removeEventListener("abort",d),r++,Promise.resolve().then(()=>o(i??O())).then(p,b).finally(()=>{r--,a()})},cancel:v=>{s=void 0,i?.removeEventListener("abort",d),b(v)}};s=t.push(f),i?.addEventListener("abort",d,{once:!0}),a()})},get active(){return r},get pending(){return t.size},concurrency:n,onIdle(){return r===0&&t.size===0?Promise.resolve():new Promise(o=>e.push(o))},clear(){for(let o=t.shift();o;o=t.shift())o.cancel(new k("HLP_ASYNC_QUEUE_CLEARED","The queued task was cleared."));l()}}}function V(){return _(1)}async function Y(n,t,r={}){const{signal:e}=r;let l=0;h(e);for await(const a of n)h(e),await t(a,l++,e)}export{_ as createLimiter,V as createSerialQueue,Y as forEachAsync,H as mapLimit,M as mapLimitSettled,D as partitionSettled};
|