i am new to currying but i have a problem that i can't solve.
function curry(func) {
return date1=>{
return date2=>{
return date3=>{
return func(date1,date2,date3);
};
};
};
}
function format_date(a,b,c){
return a+ "." + b +"."+c;
}
var date= curry(format_date);
console.log(date(1)(12)(2020));
console.log(date(1,12)(2020));
console.log(date(1)(12, 2020));
console.log(date(1,12, 2020));
the output of all logs should be
1.12.2020
but i only get the first right other return [Function(anonymous)]
You could take a double curried function for handing over the collected parameters and args.
This approach allows to use date with independent parameters.
function curry(func) {
const
fn = p => (...args) => {
const parameters = [...p, ...args];
if (parameters.length >= func.length) return func(...parameters);
return fn(parameters);
};
return fn([]);
}
function format_date(a, b, c) {
return a + "." + b + "." + c;
}
var date = curry(format_date);
console.log(date(1)(12)(2020));
console.log(date(2, 12)(2020));
console.log(date(3)(12, 2020));
console.log(date(4, 12, 2020));
Currying is an highly important aspect of functional programming. JS, once upon a time, was set to progress in the functional direction but then heads changed. Along with all it's functional capacity it's set to develop on the imperative path once again. People almost forget about getting functional in JS. Nowadays you see everybody embracing async await instead of monadic promises. Sad.
Whatever; back to your question, of course in JS you can curry a function even if it has unlimited number of arguments.
var curry = f => f.length ? (...a) => curry(f.bind(f,...a)) : f(),
That's it..!
If your to be curried function is;
function format_date(a,b,c){
return a+ "." + b +"."+c;
}
Then let us see them in action;
function format_date(a, b, c) {
return a + "." + b + "." + c;
}
var curry = f => f.length ? (...a) => curry(f.bind(f,...a)) : f(),
fDate = curry(format_date);
console.log(fDate(2021)(11)(30));