|
| 1 | +import { DaffMergeStrategy } from './strategy.type'; |
| 2 | + |
| 3 | +/** |
| 4 | + * Merges dictionaries with a specific strategy for handling collisions. |
| 5 | + * @see {@link DaffMergeStrategy}. |
| 6 | + * |
| 7 | + * @example Merging two dictionaries with predefined mergers |
| 8 | + * |
| 9 | + * ```ts |
| 10 | + * const a = { |
| 11 | + * ary: [1, 2], |
| 12 | + * obj: {foo: 5, bar: 10} |
| 13 | + * } |
| 14 | + * const a = { |
| 15 | + * ary: [3, 4], |
| 16 | + * obj: {foo: 6}, |
| 17 | + * fish: 'tacos' |
| 18 | + * } |
| 19 | + * const result = daffMerge( |
| 20 | + * [a, b], |
| 21 | + * { |
| 22 | + * ary: daffArrayConcatMerger, |
| 23 | + * obj: daffDictAssignMerger |
| 24 | + * } |
| 25 | + * ) |
| 26 | + * ``` |
| 27 | + * the value of result would be: |
| 28 | + * ```ts |
| 29 | + * { |
| 30 | + * ary: [1, 2, 3, 4], |
| 31 | + * obj: {foo: 6, bar: 10}, |
| 32 | + * fish: 'tacos' |
| 33 | + * } |
| 34 | + * ``` |
| 35 | + * |
| 36 | + * @example Merging two dictionaries with predefined mergers |
| 37 | + * |
| 38 | + * ```ts |
| 39 | + * const a = { |
| 40 | + * ary: [1, 2], |
| 41 | + * obj: {foo: 5, bar: 10} |
| 42 | + * } |
| 43 | + * const a = { |
| 44 | + * ary: [3, 4], |
| 45 | + * obj: {foo: 6}, |
| 46 | + * fish: 'tacos' |
| 47 | + * } |
| 48 | + * const result = daffMerge( |
| 49 | + * [a, b], |
| 50 | + * { |
| 51 | + * ary: daffArrayConcatMerger, |
| 52 | + * obj: daffDictAssignMerger |
| 53 | + * } |
| 54 | + * ) |
| 55 | + * ``` |
| 56 | + * the value of result would be: |
| 57 | + * ```ts |
| 58 | + * { |
| 59 | + * ary: [1, 2, 3, 4], |
| 60 | + * obj: {foo: 6, bar: 10}, |
| 61 | + * fish: 'tacos' |
| 62 | + * } |
| 63 | + * ``` |
| 64 | + */ |
| 65 | +export const daffMerge = <T extends Record<string, unknown> = Record<string, unknown>>(dicts: Array<T>, strategy: DaffMergeStrategy<T> = {}): T => |
| 66 | + dicts.reduce((acc, dict) => { |
| 67 | + for (const k in dict) { |
| 68 | + if (Object.hasOwn(acc, k) && strategy[k]) { |
| 69 | + acc[k] = strategy[k](acc[k], dict[k]); |
| 70 | + } else { |
| 71 | + acc[k] = dict[k]; |
| 72 | + } |
| 73 | + } |
| 74 | + |
| 75 | + return acc; |
| 76 | + }, <T>{}); |
0 commit comments