merge.ts
· 957 B · TypeScript
原始檔案
/**
* from project:
* https://github.com/Noah2610/i3-color-theme-editor/blob/master/src/util/merge.ts
*/
import { RecursivePartial } from "./recursivePartial";
type Dict = Record<string, unknown>;
export function merge<O extends object>(
objA: RecursivePartial<O>,
objB: RecursivePartial<O>,
): O {
const allKeys = new Set([...Object.keys(objA), ...Object.keys(objB)]);
const merged = {} as Dict;
for (const key of allKeys) {
const a = (objA as Dict)[key];
const b = (objB as Dict)[key];
merged[key] = aOrB(a, b);
}
return merged as O;
}
function aOrB(a: unknown, b: unknown): unknown {
const aIsObject = typeof a === "object";
const bIsObject = typeof b === "object";
if (a && b && aIsObject && bIsObject) {
return merge(a as Dict, b as Dict);
}
if (b && bIsObject) {
return b;
}
if (a && aIsObject) {
return a;
}
return b || a;
}
| 1 | /** |
| 2 | * from project: |
| 3 | * https://github.com/Noah2610/i3-color-theme-editor/blob/master/src/util/merge.ts |
| 4 | */ |
| 5 | |
| 6 | import { RecursivePartial } from "./recursivePartial"; |
| 7 | |
| 8 | type Dict = Record<string, unknown>; |
| 9 | |
| 10 | export function merge<O extends object>( |
| 11 | objA: RecursivePartial<O>, |
| 12 | objB: RecursivePartial<O>, |
| 13 | ): O { |
| 14 | const allKeys = new Set([...Object.keys(objA), ...Object.keys(objB)]); |
| 15 | |
| 16 | const merged = {} as Dict; |
| 17 | |
| 18 | for (const key of allKeys) { |
| 19 | const a = (objA as Dict)[key]; |
| 20 | const b = (objB as Dict)[key]; |
| 21 | merged[key] = aOrB(a, b); |
| 22 | } |
| 23 | |
| 24 | return merged as O; |
| 25 | } |
| 26 | |
| 27 | function aOrB(a: unknown, b: unknown): unknown { |
| 28 | const aIsObject = typeof a === "object"; |
| 29 | const bIsObject = typeof b === "object"; |
| 30 | |
| 31 | if (a && b && aIsObject && bIsObject) { |
| 32 | return merge(a as Dict, b as Dict); |
| 33 | } |
| 34 | |
| 35 | if (b && bIsObject) { |
| 36 | return b; |
| 37 | } |
| 38 | |
| 39 | if (a && aIsObject) { |
| 40 | return a; |
| 41 | } |
| 42 | |
| 43 | return b || a; |
| 44 | } |