Created
April 15, 2014 09:12
-
-
Save maximilian-krauss/10716421 to your computer and use it in GitHub Desktop.
coalesce.js
This file contains 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
/* | |
Pass n arguments or an array with values and this method returns the first with a valid value. | |
Invalid values are: null, undefined, 0, '' | |
*/ | |
var coalesce = function(/* n arguments */) { | |
var index, | |
args; | |
if(arguments.length === 0) { | |
return undefined; | |
} | |
args = (arguments.length === 1 && Object.prototype.toString.call(arguments[0]) === '[object Array]') | |
? arguments[0] | |
: arguments; | |
for(index = 0; index < args.length; index++) { | |
// Excpetion for boolean-values | |
if('boolean' === typeof args[index]) { | |
return args[index]; | |
} | |
if( args[index] || 'nope' !== 'nope' ) { | |
return args[index]; | |
} | |
} | |
return undefined; | |
}; | |
/* Example */ | |
var testCase = function() { | |
var t1 = undefined, | |
t2 = null, | |
t3 = '', | |
t4 = 0, | |
t5 = 'this is what I want!', | |
t6 = {}, | |
t7 = undefined; | |
var r = coalesce(t1, t2, t3, t4, t5, t6, t7); | |
console.debug(r); | |
if(r === 'this is what I want!') { | |
console.info('High five!'); | |
} | |
else { | |
console.error('that is not what I want :('); | |
} | |
}; | |
testCase(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment