Last active
August 29, 2015 14:19
-
-
Save svenwltr/2c4dcda1a578ba351712 to your computer and use it in GitHub Desktop.
Currying method with holes for JavaScript.
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
'use strict'; | |
/* | |
* Currying method. | |
* | |
* Usage: | |
* >>> function test(a, b, c) {console.log(a, b, c); } | |
* >>> c = curry(test, '->', curry.hole, '<-'); | |
* >>> c('Hello'); | |
* <<< -> Hello World <- | |
* | |
*/ | |
// We make it an object literal {} so that we can test for reference-equality | |
// via the === operator later on. | |
curry.hole = {}; | |
function curry(fn) { | |
// Curry arguments. | |
var curried = arguments; | |
return function() { | |
// Arguments to fill holes. Remainders will be appended. | |
var filler = arguments; | |
// Indices: i for curried und j for fillers. | |
var i=1; // arg 0 is fn | |
var j=0; | |
// New constructed args. | |
var args = []; | |
// Create new args from curried args and fill holes with filled args. | |
for (; i < curried.length; i++) { | |
if(curried[i] === curry.hole) { | |
args.push(filler[j++]); | |
} else { | |
args.push(curried[i]); | |
} | |
} | |
// Append remainders. | |
for (; j<filler.length;j++) { | |
args.push(filler[j]); | |
} | |
// Finally, call method. | |
return fn.apply(this, args); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment