Last Updated: March 07, 2017
·
251
· adjavaherian

Currying vs. Partial Application

Been finishing up Functional JavaScript by Mike Fogus. Pretty great read. It really helps clear up the differences between currying and partial application. I've seen a few people confuse the terms, so I wanted to post a snippet here.

//Currying vs. Partial

const add = (x, y) => x + y;
const addAny = (...args) => {
    return args.reduce((prev, next) => prev + next, 0);
}

// curry to specific depth
function curry(fun, x) {
    return function(y) {
        return fun(x, y);
    }
}

// partial to any number of arguments
function partial(/* pargs */) {

    const pargs = [...arguments];
    const fun = pargs.shift();

    return function(/* bargs */) {        
        const bargs = [...pargs, ...arguments];
        return fun.apply(fun, bargs);
    }
}


const add10 = curry(add, 10);
console.log('curry', add10(10)); // 20

const partial10 = partial(add, 10);
console.log('partial', partial10(12)); // 22

const partialAny = partial(addAny);
console.log('partialAny', partialAny(1, 2, 3, 1)); // 7