Skip to content

Instantly share code, notes, and snippets.

@dodie
Last active November 10, 2016 15:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save dodie/8a2fd7899efa42da5d418e0b48bbecfc to your computer and use it in GitHub Desktop.

Some practical examples of function composition, based on this article: https://medium.com/@chetcorcos/functional-programming-for-javascript-people-1915d8775504

const add1 = (a) => a + 1
const times2 = (a) => a * 2
const compose = (a, b) => (c) => a(b(c))
const add1OfTimes2 = compose(add1, times2)
add1OfTimes2(5) // => 11
  • check filter, map and reduce before moving on
const pipe = (fns) => (x) => fns.reduce((v, f) => f(v), x)
const times2add1 = pipe([times2, add1])
times2add1(5) // => 11

Naive approach:

const greeting = (name) => `Hello ${name}`
const greeting = (name, male=false, female=false) =>
  `Hello ${male ? 'Mr. ' : female ? 'Ms. ' : ''} ${name}`

Separate conserns with functional composition:

const formalGreeting = (name) => `Hello ${name}`
const casualGreeting = (name) => `Sup ${name}`
const male = (name) => `Mr. ${name}`
const female = (name) => `Mrs. ${name}`
const doctor = (name) => `Dr. ${name}`
const phd = (name) => `${name} PhD`
const md = (name) => `${name} M.D.`


formalGreeting(male(phd("Chet")))
const identity = (x) => x
const greet = (name, options) => {
  return pipe([
    // greeting    
    options.formal ? formalGreeting :
    casualGreeting,
    
    // prefix
    options.doctor ? doctor :
    options.male ? male :
    options.female ? female :
    identity,
    
    // suffix
    options.phd ? phd :
    options.md ?md :
    identity
  ])(name)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment