Skip to content

Instantly share code, notes, and snippets.

@maximilian-krauss
Created April 15, 2014 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximilian-krauss/10716421 to your computer and use it in GitHub Desktop.
Save maximilian-krauss/10716421 to your computer and use it in GitHub Desktop.
coalesce.js
/*
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