Created
September 10, 2015 18:15
-
-
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
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
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