Object Currying (idea)

Darren Cresswell
1 min readOct 7, 2019

--

The concept of currying is nothing new to the FP world. The idea is simple — you allow for partial application of arguments to a function by returning another function when you don’t call the function with all the arguments — the function that is then returned has the earlier values preset. eg: (note: this is not actually currying, as we aren’t creating a function that takes two arguments, but it illustrates the idea)

const mult => x => y => x*y;const multBy5 = mult(5);multBy5(6); // answer is 30

But the annoyance is that you always need to provide the arguments in the same order — or else you can’t curry, because arguments aren’t just interchangable. But what is you could use objects to curry functions? the idea would be as follows:

const mult => objCurry(["x","y"],({x, y}) => x*y);const multBy5 = mult({x: 5});multBy5({y: 6}); // 30

You could alternatively set y instead of X in the first function and then set X in the second. As its an object, the order is interchangable. A very brief POC is shown below:

function objCurry(keys, cb) {
function fn(obj) {
if (keys.some(key => !(key in obj))) {
return newObj => fn({
...obj,
...newObj
});
}
return cb(obj);
}
return fn;
}
function checker(obj) {
const {size, weight} = obj;
console.log("obj", obj);
return size * weight;
}
const ocurry = objCurry(["size","weight"], checker);const a = ocurry({size: 5});
const b = a({weight: 4});
console.log(ocurry, a, b);

Any comments?

--

--