Skip to content

Instantly share code, notes, and snippets.

@bjdixon
Created September 10, 2015 18:15
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 bjdixon/1b8097924ef0f0bb0a25 to your computer and use it in GitHub Desktop.
Save bjdixon/1b8097924ef0f0bb0a25 to your computer and use it in GitHub Desktop.
takes a function and returns a function that will only be applied if it has arguments that aren't null or undefined
function maybe(fn) {
return function () {
var args = Array.prototype.slice.call(arguments);
if (!args.length) {
return;
}
for (var index = 0, length = args.length; index < length; index += 1) {
if (args[index] == null) {
return;
}
}
return fn.apply(this, args);
}
}
// usage
var a = maybe(alert);
a(null); // doesn't call the original (alert) function
a('howdy'); // alerts 'howdy'
var plus = maybe(sum);
a(plus(3, 4)); // alerts 7
a(plus(3, null)); // plus returns early and a returns early (neither sum or alert are called)
function sum(x, y) {
return x + y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment