Created
February 26, 2014 18:34
-
-
Save jeffschwartz/9235492 to your computer and use it in GitHub Desktop.
A JavaScript implementation of partial.
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
(function(){ | |
"use strict"; | |
/** | |
* Creating a partial the hard way. | |
*/ | |
(function(){ | |
function add(x){ | |
return function(y){ | |
return x + y; | |
}; | |
} | |
/// Using the above partial to add numbers. | |
var add1 = add(1); | |
var result = add1(10); | |
console.log(result); | |
/// Using the above partial to concatenate strings. | |
var greet = add("Hello, "); | |
var greeting = greet("Mr Bojangles"); | |
console.log(greeting); | |
}()); | |
/** | |
* Creating a partial using a partial factory. | |
*/ | |
(function(){ | |
function add(a, b){ | |
return a + b; | |
} | |
function partial(func, x){ | |
if(typeof func !== "function") { | |
throw new Error("func must be a function"); | |
} | |
return function(y){ | |
return func(x, y); | |
}; | |
} | |
var add1 = partial(add, 1); | |
var result = add1(1); | |
console.log(result); | |
}()); | |
/** | |
* You can even create a partial for a function that accepts more than 2 argument. | |
*/ | |
(function(){ | |
function addFive(a, b, c, d, e){ | |
return a + b + c + d + e; | |
} | |
function partial(func) { | |
if(typeof func !== "function") { | |
throw new Error("func must be a function"); | |
} | |
var args = [].slice.call(arguments, 1); | |
return function(y){ | |
args.push(y); | |
return func.apply(undefined, args); | |
}; | |
} | |
var addFiveValues = partial(addFive, 2, 3, 4, 5); | |
var addFiveMoreValues = partial(addFive, 12, 13, 14, 15); | |
var addSomeLetters = partial(addFive, "a,", "b,", "c,", "d,"); | |
var result = addFiveValues(10); // ==> 10 | |
console.log(result); | |
result = addFiveMoreValues(11); // ==> 65 | |
console.log(result); | |
result = addSomeLetters("e"); // ==> 65 | |
console.log(result); | |
}()); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment