Understanding JavaScript Currying with a practical use case

Most used functional programming design pattern

The problem

function parseCSVNumbers(csvString){
// some logic :)
}

A common solution

function parseCSVNumbers(csvString) {
const stringNumbers = csvString.split(',')
const parsedNumbers = stringNumbers.map(stringNumber => parseInt(stringNumber))

return parsedNumbers
}
stringNumber => parseInt(stringNumber)
function oneParameterParseInt (string) { 
return parseInt(string)
}

Currying by hand solution

function curriedParseInt(string) { 
return function(radix) {
return parseInt(string, radix)
}
const parseOne = curriedParseInt('1')
const parsedNumber = parseOne(10)
const parsedNumber = curriedParseInt('1')(10)

Invert parameters order

function curryiedInvertedParseInt(radix) { 
return function(string) {
return parseInt(string, radix)
}
function parseCSVNumbers(csvString, base=10) {
const parse = radix => string => parseInt(string, radix)
const stringNumbers = csvString.split(',')
const parsedNumbers = stringNumbers.map(parse(base))

return parsedNumbers
}
function parseCSVNumbers(csvString, base=10) {
const parse = radix => string => parseInt(string, radix)
const parseDecimal = parse(base)
const stringNumbers = csvString.split(',')
const parsedNumbers = stringNumbers.map(parseDecimal)

return parsedNumbers
}

A more generic currying solution

function curry(fn) {
if (fn.length === 0) {
return fn()
}
return function bindOneParam (p) {
return curry(fn.bind(null, p))
}
}
const stringParam = curry(parseInt)
function stringParam (string) {
return curry(parseInt.bind(null, string))
}
const radixParam = stringParam('1234')
const innerBind = parseInt.bind(null, '1234')
function radixParam (radix) {
return curry(innerBind.bind(null, radix))
}
const decimalNumber = radixParam(10)
const lastBind = innerBind.bind(null, 10)

Frontend AI evangelist

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store