Add defaults

This commit is contained in:
Angelos Chalaris
2018-01-19 13:51:05 +02:00
parent 6ebecdc4f7
commit f8351649c2
2 changed files with 14 additions and 0 deletions

13
snippets/defaults.md Normal file
View File

@ -0,0 +1,13 @@
### defaults
Assigns default values for all properties in an object that are `undefined`.
Use `Object.assign()` to create a new empty object and copy the original one to maintain key order, use `Array.reverse()` and the spread operator `...` to combine the default values from left to right, finally use `obj` again to overwrite properties that originally had a value.
```js
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
```
```js
defaults({ 'a': 1 }, { 'b': 2 }, { 'b': 6 }, { 'a': 3 }); // { a: 1, b: 2 }
```