如何为柯里化函数添加额外的级别?
How can I add an extra level to a curried function?
而不是:
const fn = (ctx, a, ...rest) => {};
const fnCurried = (ctx) => (b) => (...rest) => fn(ctx, b, ...rest);
someFn("something", fnCurried(ctx));
我希望能够在顶层调用“fn”,所以我想也许将上下文存储在另一种方法中会有所帮助,但我不知道该怎么做
const fnCurried = createCtx(ctx)
someFn("something", fnCurried(fn))
在您的第一个示例中,someFn
将第二个参数作为以下形式的函数:
(b) => (...rest) => fn(ctx, b, ...rest);
在你的第二个例子中,你想保持这个行为,这意味着调用 fnCurried(fn)
必须 return 上面的函数。我们可以这样写:
const fnCurried = (fn) => (b) => (...rest) => fn(ctx, b, ...rest);
但是,如果我们只是使用它,那么我们就没有在任何地方提供上下文。这就是我们可以创建另一个名为 createCtx()
的函数的地方,它将为我们 return 上面的 fnCurried 函数,同时也关闭提供的 ctx
:
const createCtx = ctx => fn => b => (...rest) => fn(ctx, b, ...rest);
const fnCurried = createCtx(ctx);
someFn("something", fnCurried(fn));
createCtx
函数允许我们传入上下文,然后 return 为我们提供 fnCurried
,调用后可以传入 someFn
而不是:
const fn = (ctx, a, ...rest) => {};
const fnCurried = (ctx) => (b) => (...rest) => fn(ctx, b, ...rest);
someFn("something", fnCurried(ctx));
我希望能够在顶层调用“fn”,所以我想也许将上下文存储在另一种方法中会有所帮助,但我不知道该怎么做
const fnCurried = createCtx(ctx)
someFn("something", fnCurried(fn))
在您的第一个示例中,someFn
将第二个参数作为以下形式的函数:
(b) => (...rest) => fn(ctx, b, ...rest);
在你的第二个例子中,你想保持这个行为,这意味着调用 fnCurried(fn)
必须 return 上面的函数。我们可以这样写:
const fnCurried = (fn) => (b) => (...rest) => fn(ctx, b, ...rest);
但是,如果我们只是使用它,那么我们就没有在任何地方提供上下文。这就是我们可以创建另一个名为 createCtx()
的函数的地方,它将为我们 return 上面的 fnCurried 函数,同时也关闭提供的 ctx
:
const createCtx = ctx => fn => b => (...rest) => fn(ctx, b, ...rest);
const fnCurried = createCtx(ctx);
someFn("something", fnCurried(fn));
createCtx
函数允许我们传入上下文,然后 return 为我们提供 fnCurried
,调用后可以传入 someFn