Javascript 动态咖喱字符串数

Javascript 动态咖喱字符串数,javascript,currying,Javascript,Currying,我在一次工作面试中遇到一个问题,我正在努力解决。我需要实现一个函数,该函数执行以下操作: // func('hello')('world').join(':'); // should output 'hello:world' // func('hello')('world')('today').join(':'); // should output 'hello:world:today' // func('hello')('world')('today')('foo').join(':'); /

我在一次工作面试中遇到一个问题,我正在努力解决。我需要实现一个函数,该函数执行以下操作:

// func('hello')('world').join(':'); // should output 'hello:world'
// func('hello')('world')('today').join(':'); // should output 'hello:world:today'
// func('hello')('world')('today')('foo').join(':'); // should output 'hello:world:today:foo'
该逻辑需要支持使用动态数量的字符串进行货币化

到目前为止,我成功构建了以下两个解决方案,但它们不适合所需功能的相同结构:

第一个是调用最后一个调用,我可以这样做:

const prodall = (...a) => { return a.reduce((acc, item) => [...acc, item], []); };
const curry = f => (...a) => a.length ? curry(f.bind(f, ...a)) : f();
const func = curry(prodall);
console.log(func('hello')('world')('today')('foo')().join(':'));
第二个适合我的需要,但不具有动态数量的参数:

const curry = (worker, arity = worker.length) => {
    return function (...args) {
        if (args.length >= arity) {
            return worker(...args);
        } else {
            return curry(worker.bind(this, ...args), arity - args.length);
        }
    };
};

let func = curry((a, b, c) => [a, b, c]);
console.log(func('hello')('world')('today').join(':'));
func = curry((a, b, c, d) => [a, b, c, d]);
console.log(func('hello')('world')('today')('foo').join(':'));

谢谢

您可以返回以下所有函数:

  • 具有以前参数的持久数组的作用域
  • 返回具有
    join
    属性的函数对象,该属性接受该持久数组并将其联接
const func=(arg)=>{
常量args=[arg];
常量内部=(参数)=>{
args.push(arg);
返回内部;
};
inner.join=()=>args.join(“:”);
返回内部;
};
log(func('hello')('world').join(':');

log(func('hello')('world')('today')).join(':')哇,非常感谢:)