柯里化字符串的动态数量

Dynamic number of currying strings

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

// 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(':'));

谢谢!

您可以 return 功能全部:

  • 具有先前参数的持久数组的范围
  • return 一个带有 join 属性 的函数对象,它接受那个持久数组并加入它

const func = (arg) => {
  const args = [arg];
  const inner = (arg) => {
    args.push(arg);
    return inner;
  };
  inner.join = () => args.join(':');
  return inner;
};

console.log(func('hello')('world').join(':'));
console.log(func('hello')('world')('today').join(':'));