Skip to content

Instantly share code, notes, and snippets.

@jeffgca
Created December 26, 2010 21:03
Show Gist options
  • Save jeffgca/755639 to your computer and use it in GitHub Desktop.
Save jeffgca/755639 to your computer and use it in GitHub Desktop.
A goofy, async, incomplete implementation of unless
/**
* user-space unless, some syntactic sugar from ruby implemented in JS
* @var {bool} statement - any statement in JS that evaulates to a boolean. Watch for truthiness here.
* @var {function} callback - adds the shiny sheen of async programming to this.
*/
window.unless = function(statement, callback) {
var returnValue = false;
args = [].slice.call(arguments);
if (args.length > 2) {
callback = args.pop();
if (typeof(callback) !== 'function') {
throw "last argument really needs to be callable";
}
for(i in args) {
if (!args[i]) { returnValue = true;
// short-circuit. the first statement that evaluates as false breaks the chain
break;
}
}
}
else {
// inversion, because this is *unless*
(!statement) ? returnValue = true : returnValue = false;
}
if (returnValue === true) {
callback(returnValue);
}
}
// simple test
unless(2+2==5, function(val) {
// we only get here if 2 + 2 = 5
alert(val);
});
// simple test 2
unless(true, function(val) {
// we always get here
alert(val);
});
/**
* Obvious limitations - no 'else' like in ruby, but IMHO doing unless .. else is really
* bullshit anyway. You should just do if ... else. see this:
* http://railstips.org/blog/archives/2008/12/01/unless-the-abused-ruby-conditional/
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment