Last active
July 1, 2023 05:49
-
-
Save trevorhreed/14b8ecfae8950625c34b9592152d2267 to your computer and use it in GitHub Desktop.
A deep merge of options or configuration values
This file contains 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
export const merge = (target, ...sources) => { | |
target = { ...target } | |
if (!sources.length) return target | |
const source = sources.shift() | |
for(const key in source) { | |
const value = target[key] | |
const isObject = value | |
&& typeof value == 'object' | |
&& !(value instanceof Date) | |
&& !(value instanceof RegExp) | |
target[key] = isObject | |
? merge(target[key], source[key]) | |
: target[key] ?? source[key] | |
} | |
return Array.isArray(target) | |
// for my configuration/option purposes, treating arrays as sets is more useful, | |
// but it's not neceesary, if you don't mind duplicate values. | |
? Array.from(new Set([...source, ...target])) | |
: { ...source, ...target } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment