-
-
Save leecade/3036954 to your computer and use it in GitHub Desktop.
JavaScript: partial application in a useful way, like creating a function that can be passed to filter / forEach / map, etc.
This file contains hidden or 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
| /* | |
| * filterify | |
| * | |
| * Copyright (c) 2012 "Cowboy" Ben Alman | |
| * Licensed under the MIT license. | |
| * http://benalman.com/about/license/ | |
| */ | |
| Function.prototype.filterify = function filterify() { | |
| var args = arguments.length > 0 ? [].slice.call(arguments) : [filterify]; | |
| var fn = this; | |
| return function(value) { | |
| return fn.apply(this, args.map(function(arg) { | |
| return arg === filterify ? value : arg; | |
| })); | |
| }; | |
| }; |
This file contains hidden or 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
| var foo = function(a, b, c) { | |
| console.log(a, b, c); | |
| }; | |
| foo("a", "b", "c"); | |
| // a b c | |
| ["X", "Y", "Z"].forEach(foo.filterify()); | |
| // X undefined undefined | |
| // Y undefined undefined | |
| // Z undefined undefined | |
| ["X", "Y", "Z"].forEach(foo.filterify(foo.filterify, "b", "c")); | |
| // X b c | |
| // Y b c | |
| // Z b c | |
| ["X", "Y", "Z"].forEach(foo.filterify("a", foo.filterify, "c")); | |
| // a X c | |
| // a Y c | |
| // a Z c | |
| ["X", "Y", "Z"].forEach(foo.filterify("a", "b", foo.filterify)); | |
| // a b X | |
| // a b Y | |
| // a b Z |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment