Skip to content

Instantly share code, notes, and snippets.

@trevorhreed
Last active July 1, 2023 05:49
Show Gist options
  • Save trevorhreed/14b8ecfae8950625c34b9592152d2267 to your computer and use it in GitHub Desktop.
Save trevorhreed/14b8ecfae8950625c34b9592152d2267 to your computer and use it in GitHub Desktop.
A deep merge of options or configuration values
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