function currying

by Anchit Gupta

JavaScript

/* a(b(c(x,y,z))) */

//Write a util function for the above implementation

/* util(a,b,c); */

// The apporach to this is using the concept of currying 

function util(call1, call2, call3){
	return function(x,y,z){
  	let c = call3(x,y,z);
    return call1(call2(c));
  }
}

var a = (param) => {
	return param;
}
var b = (param) => {
	return param;
}
var c = (x,y,z) => {
	return x+y+z;
}

var ans = util(a,b,c)(2,3,4);
console.log("ans: ", ans);

//now for multiple functions, we need to use the arguments param

function utilMulti(...args){
	let func;
  return function(x,y,z){
    for (let i=args.length-1; i >= 0; i--){
      if (i == args.length-1){
        func = args[i](x,y,z);
      }else{
      	func = args[i](func);
      }
    }
    return func;
  }
}

var ansMulti = util(a,b,c)(2,3,4);
console.log("ansMulti: ", ansMulti);

const compose = (...fns) => x => fns.reduceRight((y, f) => f(y), x);

var ansCompose = compose(a,b,c)(2,3,4);
console.log("ansCompose: ", ansCompose);