I’m trying to implement the curry() with placeholder support, that is curriable
. curriable
provides a high performance and small footprint curry
method. The version1 is the working code
is using map in the recursion function. However, I tried to use filter to filter the placeholder in the version2! Using filter is good for most cases, but not will fail with case curriedJoin(_,_,3,4)(1,_)(2,5)
, can any one tell me why?
version 1
/**
* @param { (...args: any[]) => any } fn
* @returns { (...args: any[]) => any }
*/
// function curry(fn) {
// // your code here
// }
function curry(func) {
return function curried(...args) {
const complete = args.length >= func.length && !args.slice(0, func.length).includes(curry.placeholder);
if(complete) {
args.length=3
args.sort((a,b)=>a-b)
return func.apply(this, args)
}
return function(...newArgs) {
// replace placeholders in args with values from newArgs using map
const res = args.map(arg => arg === curry.placeholder && newArgs.length ? newArgs.shift() : arg);
return curried(...res, ...newArgs);
}
}
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
curry.placeholder = Symbol()
const curriedJoin = curry(join)
const _ = curry.placeholder
console.log(curriedJoin(1, 2, 3)) // '1_2_3'
console.log(curriedJoin(_, 2)(1, 3)) // '1_2_3'
console.log(curriedJoin(_, _, _)(1)(_, 3)(2)) // '1_2_3'
console.log(curriedJoin(_,_,3,4)(1,_)(2,5))// '1_2_3'
Version2
/**
* @param { (...args: any[]) => any } fn
* @returns { (...args: any[]) => any }
*/
// function curry(fn) {
// // your code here
// }
function curry(func) {
return function curried(...args) {
const complete = args.length >= func.length && !args.slice(0, func.length).includes(curry.placeholder);
if(complete) {
args.length=3
args.sort((a,b)=>a-b)
return func.apply(this, args)
}
return function(...newArgs) {
// replace placeholders in args with values from newArgs
const res = [...args].filter(element=> element!== curry.placeholder);
return curried(...res, ...newArgs);
}
}
}
const join = (a, b, c) => {
return `${a}_${b}_${c}`
}
curry.placeholder = Symbol()
const curriedJoin = curry(join)
const _ = curry.placeholder
console.log(curriedJoin(1, 2, 3)) // '1_2_3'
console.log(curriedJoin(_, 2)(1, 3)) // '1_2_3'
console.log(curriedJoin(_, _, _)(1)(_, 3)(2)) // '1_2_3'
console.log(curriedJoin(_,_,3,4)(1,_)(2,5)) //Fail, because "Uncaught TypeError: curriedJoin(...)(...) is not a function"