Check for the existential value of a variable/object. Assign one if the value doesn't exist.
Very useful to setup a object with default values if the user preferences are empty. Works fine with deep objects:
var defaults = {
timeout: 3000,
cb: function() {},
user: {
name: 'someone'
url: 'github.com'
}
}
var objt = {
user: {
name: 'Kiko Beats'
url: 'github.com'
}
}
existsAssign(defaults, objt)
// {
// timeout: 3000,
// cb: function() {},
// user: {
// name: 'Kiko Beats'
// url: 'github.com'
// }
// }
Notes that is slightly different than Object.assign
.
npm install existential-assign
If you want to use in the browser (powered by Browserify):
bower install existential-assign --save
and later link in your HTML:
<script src="bower_components/existential-assign/dist/existential-assign.js"></script>
First load the library:
var existsAssign = require('existential-assign');
Working with something that is not a Object
:
existsAssign('hello world', null); // => 'hello world'
existsAssign('world', 'hello'); // => 'hello'
Working with Object
:
existsAssign({hello: 'world'}, null) // => {hello: 'world'}
existsAssign({hello: 'Aloha'}, {hello: 'world'}) // => {hello: 'world'}
You can provide more than one source:
existsAssign({hello: 'world'}, null, undefined) // => {hello: 'world'}
It's equivalent to:
existsAssign(existsAssign({hello: 'world'}, null), undefined) // => {hello: 'world'}
- existential – The missing existential operator for JavaScript.
- existential-default – Check for the existential value of a variable and assign a value by default.
- existential-default-deep – Deep version of existential-default.
MIT © Kiko Beats