DEV Community

How to make functions partially applicable in JavaScript

YCM Jason on March 07, 2018

Update: Learn how to type PartiallyApplicable in TypeScript TL; DR const enablePartialApplication = (fn) => (...args) => { ...
Collapse
 
gmartigny profile image
Guillaume Martigny

If you don't care for readability, you can write it as a tiny on-liner :

const enablePartialApplication = fn => (...args) => args.length >= fn.length ? fn(...args) : enablePartialApplication(fn.bind(null, ...args));

It nice to have such power in one line.

Collapse
 
tarik12009 profile image
tarik12009 • Edited

I believe that this concept is called "Currying" : en.wikipedia.org/wiki/Currying

Collapse
 
srishanbhattarai profile image
Srishan Bhattarai

FP 101 - Currying vs. Partial application

Currying is converting one function of arity n into n functions of arity one.
There is no requirement that partial application be bound to a particular arity (one, in the case of currying), it simply states that if you call a function with only some of the arguments - you get back another function "binds" or "fixes" the arguments that you passed in, as demonstrated by the author here. It's a very prevalent concept in FP languages like Haskell.

Collapse
 
ycmjason profile image
YCM Jason • Edited

Thanks for clarifying this! I did do my research before deciding what keyword to use. I also thought curry is the same as partial function application. It's great someone could verify my word choice! :D

Collapse
 
srishanbhattarai profile image
Srishan Bhattarai

If nothing else, it forces you to think in ways you wouldn't otherwise. I believe Larry Wall (creator of Perl) recommends Haskell as an "academic" language for this reason :)

Collapse
 
inf3rno profile image
inf3rno • Edited

It can be useful if you design a library and you are thinking on the proper api. It can be combined for example with fluent interface: x(a).y(b)(c) etc. So it is good only for sugar syntax.

Collapse
 
bernardoow profile image
Bernardo Gomes

I used partial function with elm-lang.
Thanks for sharing !!