-3

How could I write a javascript function knowing whether it needs to be curried?

fifn2
  • 382
  • 1
  • 6
  • 15
  • The overwhelming corpus of existing javascript code does not use currying at all, and functional programming concepts are alien to many. Why use it at all? – spender Aug 28 '18 at 15:20
  • 1
    Rule of thumb: when you have a function with > 2 parameters and one(some) of them changes rarely if ever and the other(s) change frequently. Example: if you debounce a lot of different event handlers with the same timeout you probably should curry (or at least partially apply) your debounce function. – Jared Smith Aug 29 '18 at 18:32

1 Answers1

1

There is at least one case I see where currying your function can help you write better code, in terms of performance.

Let's say I have a template renderer.

const templateRenderer = (template, ...args) => {
  const preProcessedTemplate = preProcess(template)
  return preProcessedTemplate.render(...args)
}

const template = new Template(.......)
const renderedContent1 = templateRender(template, 1)
const renderedContent2 = templateRender(template, 2)
const renderedContent3 = templateRender(template, 3)

Let's say preProcess is the costly function, and preProcessedTemplate.render runs fast. In the previous code, preProcess is called 3 times.

The first step does not depend on args. Therefore this code will give the same result :

const makeTemplateRenderer = template => {
  const preProcessedTemplate = preProcess(template)
  return (...args) => preProcessedTemplate.render(...args)
}

const template = new Template(.......)
const templateRenderer = makeTemplateRenderer(template)
const renderedContent1 = templateRender(1)
const renderedContent2 = templateRender(2)
const renderedContent3 = templateRender(3)

In this case, preProcess is only called once. Currying your function (and performing intermediate steps in between) has lead to better performance.

Aymeric Bouzy aybbyk
  • 2,031
  • 2
  • 21
  • 29
  • 1
    I can see infinite cases, but without more context, this question becomes a list of speculative answers. – spender Aug 28 '18 at 15:49