Skip to content

Instantly share code, notes, and snippets.

@pauladam
Created March 10, 2011 01:29
Show Gist options
  • Save pauladam/863404 to your computer and use it in GitHub Desktop.
Save pauladam/863404 to your computer and use it in GitHub Desktop.
Practical example of function currying in JS
// I have some code that needs to use the following
// construct repeatedly
for(i=0;i<classes.length;i++){
var c = classes[i];
for(j=0;j<centers.length;j++){
var k = centers[k];
// do something with [c,k], like,
// demand[[c,k]] = expression;
}
}
// The looping constructs are going to be duplicated
// many times, so Im going to abstract it out
// abstraction for double nested loops
var doubleListIterator = function(list1, list2, f){
list1.forEach(function(c, i){
list2.forEach(function(k, j){
f(c,k,i,j);
});
});
}
// now I can do this
doubleListIterator(['a', 'b', 'c'], [1,2,3], function(el1, el2){
console.log(el1, el2);
}
// prints,
// a 1
// b 2
// c 3
// great, but what if I want a double list iterator that always
// uses a certain 2 arguments (in my case 'classes' and 'centers',
// then we should curry this function to 'bind' the arguments
// so they dont need to be passed in explicitly each time
// simple currying function
var partial = function(f, list1, list2){
return function(nf){
f(list1, list2, nf);
}
}
// construct my special curried iterator
var ckIterator = partial(doubleListIterator, classes, centers);
// now instead of the super wordy thing up top, I can simply do,
ckIterator(function(c,k){
// c, k here come from 'classes' and 'centers'
// and have been bound to this curried function
// do something w/ c and k
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment