Created
April 8, 2012 17:48
-
-
Save tblobaum/2338725 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // returns the first defined argument, which is useful for cleanly | |
| // setting values with multiple potential defaults | |
| function defined () { | |
| for (var i=0; i<arguments.length; i++) | |
| if (typeof arguments[i] !== 'undefined') | |
| return arguments[i] | |
| } | |
| 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 }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment