sergeq
Last Updated: March 07, 2017
·
56
· adjavaherian
57bd1e5e501e4ea94775008353e39b22

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
Say Thanks
Respond
Awesome Job

9f636f3e 6e39 11e7 9fd5 de0ca15231c3
Software Engineer
·
St. Thomas, VI, or Landenberg, PA
·
Full Time