Skip to content

Instantly share code, notes, and snippets.

@leecade
Forked from cowboy/filterify.js
Created July 3, 2012 01:32
Show Gist options
  • Select an option

  • Save leecade/3036954 to your computer and use it in GitHub Desktop.

Select an option

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.
/*
* 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;
}));
};
};
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