gist: 2338725, 2012-04-08 17:48:16Z
// returns the first defined argument, which is useful for cleanly
// setting values with multiple potential defaults
function defined () {
Array.prototype.slice.call(arguments).reverse().forEach(function (arg) {
if (typeof arg !== 'undefined')
retval = arg
})
return retval
}
var baz = false
// example
function example (options) {
options = defined(options, {})
var foo = defined(options.foo, 'foo-default-value')
, bar = defined(options.bar, baz, 'bar-default-value')
console.log(options, foo, bar)
}
example({ foo: false })
// typical pseudo-equivalent, which merely tests for falsy values
function badIdea (options) {
options = options || {}
var foo = options.foo || 'foo-default-value'
, bar = options.bar || baz || 'bar-default-value'
console.log(options, foo, bar)
}
badIdea({ foo: false })
// actual equivalent, which is fairly verbose
function equivalent (options) {
var foo
, bar
if (typeof options == 'undefined') {
options = {}
}
if (typeof options.foo != 'undefined') {
foo = options.foo
}
else {
foo = 'foo-default-value'
}
if (typeof options.bar != 'undefined') {
bar = options.bar
}
else if (typeof baz != 'undefined') {
bar = baz
}
else {
bar = 'bar-default-value'
}
console.log(options, foo, bar)
}
equivalent({ foo: false })