Skip to content

Instantly share code, notes, and snippets.

@AntsiferovMaxim
Created March 3, 2020 11:57
Show Gist options
  • Save AntsiferovMaxim/c5a9e0ed4a04e713bbfcca739e8c9316 to your computer and use it in GitHub Desktop.
Save AntsiferovMaxim/c5a9e0ed4a04e713bbfcca739e8c9316 to your computer and use it in GitHub Desktop.
export function defaultsDeep(object: object | Array<any>, ...sources: any[]) {
return sources.reduce((acc, source) => customDefaultsDeep(acc, source), object);
}
function customDefaultsDeep(object, source) {
if (Array.isArray(source)) {
if (object === undefined) {
object = []
}
if (source.length < object.length) {
return object.map((item, key) => merge(source, object, key, customDefaultsDeep))
} else {
return source.map((item, key) => merge(object, source, key, customDefaultsDeep))
}
} else {
if (object === undefined) {
object = {}
}
return Object.keys(source).reduce((acc, key) => {
acc[key] = merge(object, source, key, customDefaultsDeep);
return acc
}, object)
}
}
function merge(object, source, key, rec) {
return isPrimitive(source[key])
? object[key] === undefined
? source[key]
: object[key]
: rec(object[key], source[key])
}
function isPrimitive(test) {
return test !== Object(test)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment