Created
March 3, 2020 11:57
-
-
Save AntsiferovMaxim/c5a9e0ed4a04e713bbfcca739e8c9316 to your computer and use it in GitHub Desktop.
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 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