ceghap
8/17/2017 - 10:07 AM

Example of currying in js

Example of currying in js

There are benefits to use currying in your code. One of it is the ability to 'refactor' your code and make it DRY. Compare this two code of none currying and currying code. See the structure of both code.

none currying code

let dragon = (name, size, element) => 
  name + ' is a ' +
  size + ' dragon that breathes ' +
  element + '!'

console.log(dragon('jojo', 'big', 'fire'))

currying code

let dragon = 
  name =>
    size =>
      element =>
        name + ' is a ' +
        size + ' dragon that breathes ' +
        element + '!'

let output = dragon('jojo')('big')('fire')

console.log(output)

Above code shows when currying, we call the function with (args)(args)(args). But if you have a none currying code and need to make it currying there is a way. Here I will use lodash to do it. Install it if you haven't.

import _ from 'lodash'
let dragon = (name, size, element) => 
  name + ' is a ' +
  size + ' dragon that breathes ' +
  element + '!'

dragon = _.curry(dragon)

let jojoDragon = dragon('jojo')
let bigDragon = jojoDragon('big')

console.log(bigDragon('fire'))

Here is more 'advance' example of currying code.

import _ from 'lodash'

let dragons = [
  { name: 'fluffykins', element: 'lightning'},
  { name: 'noomi', element: 'lightning'},
  { name: 'karo', element: 'fire'},
  { name: 'doomer', element: 'timewrap'},
]

let hasElement =
  _.curry((element, obj) => obj.element === element) 

let lightingDragons =
  dragons.filter(hasElement('lightning'))

console.log(lightingDragons)