-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patharray_helpers.ts
More file actions
341 lines (270 loc) · 11.3 KB
/
array_helpers.ts
File metadata and controls
341 lines (270 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import type { Closure, Falsy } from '@noeldemartin/utils/types/helpers';
import type { DeepKeyOf } from '@noeldemartin/utils/types/objects';
import { compare } from './logical_helpers';
import { deepGet, isIterable, isString, toString } from './object_helpers';
export type ArrayFrom<T> = T extends Iterable<infer TItem> ? TItem[] : T[];
export function arrayClear(items: unknown[]): void {
items.splice(0, items.length);
}
export function arrayDiff<T>(
original: T[],
updated: T[],
compareValues?: (a: T, b: T) => boolean,
): { added: T[]; removed: T[] } {
const removed = original.slice(0);
const added = [];
const search: (item: T, items: T[]) => number = compareValues
? (item, items) => items.findIndex((otherItem) => compareValues(item, otherItem))
: (item, items) => items.indexOf(item);
for (const updatedItem of updated) {
const index = search(updatedItem, removed);
index !== -1 ? removed.splice(index, 1) : added.push(updatedItem);
}
return { added, removed };
}
export function arrayChunk<T>(items: T[], chunkSize: number): T[][] {
const chunks = [];
for (let i = 0; i < items.length; i += chunkSize) {
chunks.push(items.slice(i, i + chunkSize));
}
return chunks;
}
export function arrayEquals<T>(original: T[], updated: T[]): boolean {
if (original.length !== updated.length) {
return false;
}
return !original.some((value, index) => updated[index] !== value);
}
export function arrayFilter<T>(items: (T | Falsy)[]): T[];
export function arrayFilter<T>(items: T[], filter: (item: T) => boolean): T[];
export function arrayFilter<T>(items: T[], filter?: (item: T) => boolean): T[] {
return filter ? items.filter(filter) : items.filter((item) => !!item);
}
export function arrayFirst<T>(items: T[], filter: (item: T) => boolean): T | null {
for (const item of items) {
if (!filter(item)) continue;
return item;
}
return null;
}
export function arrayFlatMap<T, R>(items: T[], map: (item: T, index: number) => R[]): R[] {
return [...items.entries()].flatMap(([index, item]) => map(item, index));
}
export function arrayWithItemAt<T>(items: T[], item: T, index: number): T[] {
return [...items.slice(0, index + 1), item, ...items.slice(index + 1)];
}
export function arrayGroupBy<TItem, TKey extends string>(
items: TItem[],
groupBy: (item: TItem) => TKey
): Partial<Record<TKey, TItem[]>>;
export function arrayGroupBy<TItem, TKey extends keyof TItem>(items: TItem[], groupBy: TKey): Record<string, TItem[]>;
export function arrayGroupBy<TItem>(
items: TItem[],
groupBy: string | ((item: TItem) => string),
): Partial<Record<string, TItem[]>> {
const group =
typeof groupBy === 'string' ? (item: TItem) => toString(item[groupBy as unknown as keyof TItem]) : groupBy;
return items.reduce(
(groups, item) => {
(groups[group(item)] ??= []).push(item);
return groups;
},
{} as Record<string, TItem[]>,
);
}
export function arrayIsEmpty(items: unknown[]): boolean {
return items.length === 0;
}
export function arrayProject<T, S extends keyof T>(items: T[], property: S): T[S][] {
return items.map((item) => item[property]);
}
export function arrayPull<T>(items: T[], index: number): T | undefined {
const value = items[index];
items.splice(index, 1);
return value;
}
export function arrayRandomItem<T>(items: T[]): T | null {
return items.length === 0 ? null : (items[Math.floor(Math.random() * items.length)] as T);
}
export function arrayRandomItems<T>(items: T[], count: number): T[] {
const itemsLeft = items.slice(0);
const randomItems = [] as T[];
while (itemsLeft.length > 0 && randomItems.length < count) {
const index = Math.floor(Math.random() * itemsLeft.length);
randomItems.push(itemsLeft[index] as T);
itemsLeft.splice(index, 1);
}
return randomItems;
}
export function arrayRemove<T>(items: T[], item: T): boolean {
const index = items.indexOf(item);
if (index === -1) return false;
items.splice(index, 1);
return true;
}
export function arrayRemoveIndex<T>(items: T[], index: number | string): boolean {
return items.splice(Number(index), 1).length > 0;
}
export function arrayReplace<T>(items: T[], original: T, replacement: T): boolean {
const index = items.indexOf(original);
if (index === -1) return false;
items[index] = replacement;
return true;
}
export function arraySorted<T>(items: T[]): T[];
export function arraySorted<T>(items: T[], direction: 'asc' | 'desc'): T[];
export function arraySorted<T>(items: T[], compareValues: (a: T, b: T) => number): T[];
export function arraySorted<T>(items: T[], field: DeepKeyOf<T>, direction?: 'asc' | 'desc'): T[];
export function arraySorted<T>(items: T[], fields: DeepKeyOf<T>[], direction?: 'asc' | 'desc'): T[];
export function arraySorted<T>(
items: T[],
compareOrFieldOrDirection?: DeepKeyOf<T> | DeepKeyOf<T>[] | ((a: T, b: T) => number) | 'asc' | 'desc',
direction?: 'asc' | 'desc',
): T[] {
direction =
compareOrFieldOrDirection === 'asc' || compareOrFieldOrDirection === 'desc'
? (compareOrFieldOrDirection as 'asc' | 'desc')
: direction;
const fieldDefaults: Partial<Record<DeepKeyOf<T>, unknown>> = {};
const getDefaultValue = (sample: unknown): unknown => {
switch (typeof sample) {
case 'string':
return '';
case 'number':
return Number.MIN_SAFE_INTEGER;
case 'boolean':
return false;
default:
return null;
}
};
const getFieldValue = (object: T, field: DeepKeyOf<T>): unknown => {
if (!(field in fieldDefaults)) {
const sampleValue = deepGet(
items.find(
(item) =>
deepGet(item as object, field as never) !== undefined &&
deepGet(item as object, field as never) !== null,
) as object,
field as never,
);
fieldDefaults[field] = getDefaultValue(sampleValue);
}
return deepGet(object as object, field as never) ?? fieldDefaults[field];
};
const getComparisonFunction = (): Closure<[T, T], number> | undefined => {
const compareItems =
direction === 'desc'
? (field: DeepKeyOf<T>) => (a: T, b: T) => compare(getFieldValue(b, field), getFieldValue(a, field))
: (field: DeepKeyOf<T>) => (a: T, b: T) => compare(getFieldValue(a, field), getFieldValue(b, field));
switch (typeof compareOrFieldOrDirection) {
case 'function':
return compareOrFieldOrDirection;
case 'string':
if (compareOrFieldOrDirection === 'asc') return;
if (compareOrFieldOrDirection === 'desc') return (a, b) => compare(b, a);
return compareItems(compareOrFieldOrDirection);
case 'object': {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const comparisonFunctions = compareOrFieldOrDirection.map((field: any) => compareItems(field));
return (a: T, b: T) => {
for (const comparisonFunction of comparisonFunctions) {
const result = comparisonFunction(a, b);
if (result !== 0) return result;
}
return 0;
};
}
}
};
return items.slice(0).sort(getComparisonFunction());
}
export function arraySwap(items: unknown[], firstIndex: number, secondIndex: number): void {
[items[firstIndex], items[secondIndex]] = [items[secondIndex], items[firstIndex]];
}
export function arrayUnique<T>(items: T[], extractKey?: (item: T) => string): T[] {
return extractKey
? Object.values(
items.reduce(
(unique, item) => {
const key = extractKey(item);
unique[key] = unique[key] ?? item;
return unique;
},
{} as Record<string, T>,
),
)
: [...new Set(items)];
}
export function arrayFind<T, K extends keyof T>(items: T[], filter: string, value?: T[K]): T | undefined {
return items.find((item) => {
const property = item[filter as keyof T];
const result = typeof property === 'function' ? property.call(item) : property;
return value ? result === value : !!result;
});
}
export function arrayWhere<T, K extends keyof T>(items: T[], filter: string, value?: T[K]): T[] {
return items.filter((item) => {
const property = item[filter as keyof T];
const result = typeof property === 'function' ? property.call(item) : property;
return value ? result === value : !!result;
});
}
export function arrayWithout<T>(items: T[], exclude: T | T[]): T[] {
return Array.isArray(exclude)
? arrayFilter(items, (item) => exclude.indexOf(item) === -1)
: arrayWithoutIndex(items, items.indexOf(exclude));
}
export function arrayWithoutIndex<T>(items: T[], index: number): T[] {
return arrayWithoutIndexes(items, [index]);
}
export function arrayWithoutIndexes<T>(items: T[], indexes: number[]): T[] {
return items
.map((value, index) => [value, index] as [T, number])
.filter(([_, index]) => !indexes.includes(index))
.map(([value]) => value);
}
export function arrayZip<T>(...arrays: T[][]): T[][] {
const zippedArrays: T[][] = [];
const arraysLength = arrays[0]?.length ?? 0;
for (let i = 0; i < arraysLength; i++) zippedArrays.push(arrays.map((a) => a[i] as T));
return zippedArrays;
}
export function arrayFrom<TValue, TOptions extends { ignoreEmptyValues?: boolean }>(
value: TValue,
options?: TOptions,
): TOptions extends { ignoreEmptyValues: true } ? ArrayFrom<NonNullable<TValue>> : ArrayFrom<TValue> {
const ignoreEmptyValues = options?.ignoreEmptyValues ?? false;
const items =
Array.isArray(value) || (isIterable(value) && !isString(value))
? Array.from(value)
: ignoreEmptyValues && (value === null || value === undefined)
? []
: [value];
return items as TOptions extends { ignoreEmptyValues: true } ? ArrayFrom<NonNullable<TValue>> : ArrayFrom<TValue>;
}
export function hasItems<T>(array: T[]): array is [T, ...T[]] {
return array.length > 0;
}
export function range(length: number): number[] {
return Array.from({ length }, (_, item) => item);
}
export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
items: TItem[],
key: TKey,
project: (item: TItem) => TProjection
): Record<string, TProjection>;
export function reduceBy<TItem, TKey extends keyof TItem>(items: TItem[], key: TKey): Record<string, TItem>;
export function reduceBy<TItem, TKey extends keyof TItem, TProjection>(
items: TItem[],
key: TKey,
project?: (item: TItem) => TProjection,
): Record<string, TProjection> {
return items.reduce(
(acc, item) => {
acc[toString(item[key])] = project ? project(item) : (item as unknown as TProjection);
return acc;
},
{} as Record<string, TProjection>,
);
}