如何解决柯里化字符串的动态数量
我在求职面试中遇到了一个我正在努力解决的问题。我需要实现一个执行以下操作的函数:
// 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(':'));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。