柯里化字符串的动态数量

问题描述

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

// 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,c]);
console.log(func('hello')('world')('today').join(':'));
func = curry((a,c,d) => [a,d]);
console.log(func('hello')('world')('today')('foo').join(':'));

谢谢!

解决方法

你可以返回所有的函数:

  • 具有先前参数的持久数组的范围
  • 返回一个带有 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(':'));