Created
December 18, 2021 00:11
-
-
Save davidmfoley/839776c4953f799885bde0870caecec2 to your computer and use it in GitHub Desktop.
Simplest typescript merge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const merge = (a: any, b: any): any => { | |
if ((typeof b !== "undefined" && typeof b !== "object") || Array.isArray(b)) | |
return b; | |
if ((typeof a !== "undefined" && typeof a !== "object") || Array.isArray(a)) | |
return a; | |
a ||= {}; | |
b ||= {}; | |
const keys = [...new Set([...Object.keys(a), ...Object.keys(b)])]; | |
return keys.reduce( | |
(obj, k) => ({ | |
...obj, | |
[k]: merge(a[k], b[k]), | |
}), | |
{} | |
); | |
}; | |
test("shallow", () => { | |
expect(merge({ a: 1 }, { b: 2 })).toEqual({ a: 1, b: 2 }); | |
}); | |
test("deep", () => { | |
expect(merge({ a: { x: 1 } }, { a: { y: 2 } })).toEqual({ | |
a: { x: 1, y: 2 }, | |
}); | |
}); | |
test("2nd one wins", () => { | |
expect(merge({ a: { x: 1 } }, { a: { x: 2 } })).toEqual({ | |
a: { x: 2 }, | |
}); | |
}); | |
test("nothing on right", () => { | |
expect(merge({ a: { x: 1 } }, {})).toEqual({ | |
a: { x: 1 }, | |
}); | |
}); | |
test("nothing on left", () => { | |
expect(merge({}, { a: { x: 1 } })).toEqual({ | |
a: { x: 1 }, | |
}); | |
}); | |
test("arrays", () => { | |
expect(merge({}, { a: [1, 2, 3] })).toEqual({ | |
a: [1, 2, 3], | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment