How can I add an extra level to a curried function?

Viewed 44

Instead of:

const fn = (ctx, a, ...rest) => {};
const fnCurried = (ctx) => (b) => (...rest) => fn(ctx, b, ...rest);

someFn("something", fnCurried(ctx));

I would like to be able to call "fn" at top level, so I thought maybe storing the context in another method would help, I have no idea how to go about doing this

const fnCurried = createCtx(ctx)
someFn("something", fnCurried(fn))
1 Answers

In your first example, someFn takes a second argument as a function of the form:

(b) => (...rest) => fn(ctx, b, ...rest);

In your second example, you want to keep this behaviour, this means calling fnCurried(fn) must return the above function. We can do this by writing:

const fnCurried = (fn) => (b) => (...rest) => fn(ctx, b, ...rest);

However, if we just use this, then we haven't supplied the context anywhere. That's where we can make another function called createCtx() that will return the above fnCurried function for us, while also closing over a supplied ctx:

const createCtx = ctx => fn => b => (...rest) => fn(ctx, b, ...rest);
const fnCurried = createCtx(ctx);
someFn("something", fnCurried(fn));

The createCtx function allows us to pass in the context, which then returns fnCurried for us, that can be passed into someFn once called

Related