core3-utils

@wixc3/common on Github

Home > @wixc3/common > defaults

defaults() function

Returns an object where missing keys and values/keys that satisfy shouldUseDefault to the value in shouldUseDefault.

Signature:

export declare function defaults<S extends object, D extends object>(_source: S, _defaultValues: D, deep?: boolean, shouldUseDefault?: (v: unknown, _key: string) => boolean): S & D;

Parameters

Parameter Type Description
\_source S
\_defaultValues D
deep boolean _(Optional)_ \[true\] perform a deep comparison
shouldUseDefault (v: unknown, \_key: string) => boolean _(Optional)_ value/key for which shouldUseDefault returns true will be taken from defaultValues, ignoring source. k is provided as a dot separated path

Returns:

S & D

a new object with merged source and defaultValues

Example 1

defaults({}, {a:0}) // => {a:0}
defaults({a:1}, {a:0}) // => {a:1}
defaults({a:{}}, {a:{b:1}}) // => {a:{b:1}}

by default, any undefined value will be replaced

Example 2

defaults({a:{}}, {a:{b:1}}, false) // => {a:{}}

Example 3

defaults({a:{b:1}}, {a:{b:2}}, true, (_,k)=>k==='a.b') // => {a:{b:2}}
defaults({a:1}, {a:2}, true, v=>v===1) // => {a:2}