-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.ts
383 lines (365 loc) · 7.53 KB
/
merge.ts
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/**
* @file merge.ts
* @copyright 2020-2024 Brandon Kalinowski (brandonkal)
* @author jk authors
* @description Provides generic object merging functions. Useful for config generation.
* Portions of this work were obtained via the Apache 2.0 License.
* That original work is Copyright 2020, jk authors.
*/
import { isObject } from "./utils.ts";
function mergeFunc(rules: Record<string, any>, key: string, defaultFunc: any) {
const f = rules && rules[key];
if (f === undefined) {
return defaultFunc;
}
const t = typeof f;
if (t === "object") {
return deep(f);
}
if (t !== "function") {
throw new Error(
`merge: expected a function in the rules objects but found a ${t}`,
);
}
return f;
}
/**
* objectMerge implementation
* @internal
*/
function objectMerge2<A extends Record<string, any>>(
a: A,
b: A,
rules: MergeObject<A>,
): A {
const r = {} as Record<string, any>;
Object.assign(r, a);
for (const [key, value] of Object.entries(b)) {
r[key] = mergeFunc(rules, key, merge)(a[key], value);
}
return r as A;
}
function assertObject(o: any, prefix: string) {
if (!isObject(o)) {
throw new Error(`${prefix}: input value is not an object`);
}
}
function assertArray(o: unknown, prefix: string) {
if (!Array.isArray(o)) {
throw new Error(`${prefix}: input is not an array`);
}
}
/**
* Merge strategy deep merging objects.
*
* @param rules optional set of merging rules.
*
* `deep` will deep merge objects. This is the default merging strategy of
* objects. It's possible to provide a set of rules to override the merge
* strategy for some properties. See [[merge]].
*/
export function deep(rules?: MergeObject<any>) {
return <T extends object>(a: T, b: T): T => {
if (a === undefined) a = {} as T;
if (b === undefined) b = {} as T;
assertObject(a, "deep");
assertObject(b, "deep");
return objectMerge2(a, b, rules as any);
};
}
/**
* Merge strategy merging two values by selecting the first value.
*
* **Example**:
*
* ```js
* let a = {
* k0: 1,
* o: {
* o0: 'a string',
* },
* };
*
* let b = {
* k0: 2,
* k1: true,
* o: {
* o0: 'another string',
* },
* };
*
* merge(a, b, { o: first() });
* ```
*
* Will give the result:
*
* ```js
* {
* k0: 2,
* k1: true,
* o: {
* o0: 'a string',
* },
* }
* ```
*/
export function first() {
return <A>(a: A, _: any): A => a;
}
/**
* Merge strategy merging two values by selecting the second value.
*
* **Example**:
*
* ```js
* let a = {
* k0: 1,
* o: {
* o0: 'a string',
* o1: 'this will go away!',
* },
* };
*
* let b = {
* k0: 2,
* k1: true,
* o: {
* o0: 'another string',
* },
* };
*
* merge(a, b, { o: replace() });
* ```
*
* Will give the result:
*
* ```js
* {
* k0: 2,
* k1: true,
* o: {
* o0: 'another string',
* },
* }
* ```
*/
export function replace() {
return <B>(_: any, b: B): B => b;
}
function arrayMergeWithKey<A extends Array<any>>(
a: A,
b: A,
mergeKey: string,
rules?: MergeObject<A>,
) {
const r = Array.from(a);
const toAppend: any[] = [];
for (const value of b) {
const i = a.findIndex((o) => o[mergeKey] === value[mergeKey]);
if (i === -1) {
// Object doesn't exist in a, save it in the list of objects to append.
toAppend.push(value);
continue;
}
r[i] = objectMerge2(a[i], value, rules as any);
}
Array.prototype.push.apply(r, toAppend);
return r;
}
/**
* Merge strategy for arrays of objects, deep merging objects having the same
* `mergeKey`.
*
* @param mergeKey key used to identify the same object.
* @param rules optional set of rules to merge each object.
*
* **Example**:
*
* ```js
* importee { merge, deep, deepWithKey } from '@jkcfg/std/merge';
*
* const pod = {
* spec: {
* containers: [{
* name: 'my-app',
* image: 'busybox',
* command: ['sh', '-c', 'echo Hello Kubernetes!'],
* },{
* name: 'sidecar',
* image: 'sidecar:v1',
* }],
* },
* };
*
* const sidecarImage = {
* spec: {
* containers: [{
* name: 'sidecar',
* image: 'sidecar:v2',
* }],
* },
* };
*
* merge(pod, sidecarImage, {
* spec: {
* containers: deepWithKey('name'),
* },
* });
* ```
*
* Will give the result:
*
* ```js
* {
* spec: {
* containers: [
* {
* command: [
* 'sh',
* '-c',
* 'echo Hello Kubernetes!',
* ],
* image: 'busybox',
* name: 'my-app',
* },
* {
* image: 'sidecar:v2',
* name: 'sidecar',
* },
* ],
* },
* }
* ```
*/
export function deepWithKey(mergeKey: string, rules?: MergeObject<any>) {
return <T extends Array<any>>(a: T, b: T) => {
assertArray(a, "deepWithKey");
assertArray(b, "deepWithKey");
return arrayMergeWithKey(a, b, mergeKey, rules);
};
}
/**
* Merges `b` into `a` with optional merging rule(s).
*
* @param a Base value.
* @param b Merge value.
* @param rule Set of merge rules.
*
* `merge` will recursively merge two values `a` and `b`. By default:
*
* - if `a` and `b` are primitive types, `b` is the result of the merge.
* - if `a` and `b` are arrays, `b` is the result of the merge.
* - if `a` and `b` are objects, every own property is merged with this very
* set of default rules.
* - the process is recursive, effectively deep merging objects.
*
* if `a` and `b` have different types, `merge` will throw an error.
*
* **Examples**:
*
* Merge primitive values with the default rules:
*
* ```js
* merge(1, 2);
*
* > 2
* ```
*
* Merge objects with the default rules:
*
* ```js
* const a = {
* k0: 1,
* o: {
* o0: 'a string',
* },
* };
*
* let b = {
* k0: 2,
* k1: true,
* o: {
* o0: 'another string',
* },
* }
*
* merge(a, b);
*
* >
* {
* k0: 2,
* k1: true,
* o: {
* o0: 'another string',
* }
* }
* ```
*
* **Merge strategies**
*
* It's possible to override the default merging rules by specifying a merge
* strategy, a function that will compute the result of the merge.
*
* For primitive values and arrays, the third argument of `merge` is a
* function:
*
* ```js
* const add = (a, b) => a + b;
* merge(1, 2, add);
*
* > 3
* ```
*
* For objects, each own property can be merged with different strategies. The
* third argument of `merge` is an object associating properties with merge
* functions.
*
* ```js
* // merge a and b, adding the values of the `k0` property.
* merge(a, b, { k0: add });
*
* >
* {
* k0: 3,
* k1: true,
* o: {
* o0: 'another string',
* }
* }
* ```
*/
export function merge<A>(a: A, b: A, rule?: MergeObject<A>): any {
if (a === b) {
return a;
}
const [typeA, typeB] = [typeof a, typeof b];
if (a == null) {
return b;
} else if (b === undefined) {
return a;
}
if (typeA !== typeB) {
throw new Error(
`merge cannot combine values of types ${typeA} and ${typeB}`,
);
}
// Primitive types and arrays default to being replaced.
if (Array.isArray(a) || typeA !== "object") {
if (typeof rule === "function") {
return (rule as MergeFunction<A>)(a, b);
}
return b;
}
// Objects. We cast as any because we know it to be an object
return objectMerge2(a as any, b, rule as any);
}
/** MergeObject is an object containing merge functions or a MergeFunction */
export type MergeObject<T> = T extends object ? Partial<
{
[P in keyof T]: T[P] extends object ? MergeObject<T[P]>
: MergeFunction<T[P]>;
}
>
: MergeFunction<T>;
/** MergeFunction is a function that merges two values */
export type MergeFunction<A> = (a: A, b: A) => A;