// https://postd.cc/functional-programming-for-javascript-people-1/

const sample1 = () => {
  const greeting = (name) => `Hello, ${name}!`
  console.log(greeting('harhogefoo'))
}

const sample2 = () => {
  // pure function
  const add10 = (a) => a + 10
  // impure function due to external non-constants
  let x = 10
  const addx = (a) => a + x
  // also impure due to side-effect
  const setx = (v) => x = v
  
  console.log(add10(1))
  console.log(addx(1))
  setx(2)
  console.log(x)
}

const sample3 = () => {
  const add1 = (a) => a + 1
  const times2 = (a) => a * 2
  const compose = (fnA, fnB) => (c) => fnA(fnB(c))
  const add10OfTimes2 = compose(add1, times2)
  console.log(add10OfTimes2(5)) // => 11
}

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

const pipe = (fns) => (x) => fns.reduce((v, f) => f(v), x)

const sample5 = () => {
  // good practice
  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.`
  console.log(formalGreeting(male(phd("Chet"))))
  
  const  identity = (x) => x
  const greet = (name, options) => {
    return pipe([
      // prefix
      options.doctor ? doctor : options.male ? male : options.female ? female : identity,
      // suffix
      options.phd ? phd : options.md ? md : identity,
      // greeting
      options.formal ? formalGreeting : casualGreeting,
    ])(name)
  }
  console.log(greet('harhogefoo', { formal: false, male: true }))
}

const env = (...args) => {
  args.forEach(fn => {
    console.log(`--- exec: ${fn.name} ---`)
    fn()
    console.log(`--- finish --- `)
  })
}

const sample6 = () => {
  // have to import Ramda.js
  const add = R.curry((a, b) => a + b)
  console.log(add (1, 2)) // => 3
  const add1 = add(1)
  console.log(add1(2)) // => 3
  console.log(add1(10)) // => 11
}

const sample7 = () => {
  const users = [
    {name: 'chet', age: 25},
    {name: 'joe', age: 24},
  ]
  console.log(R.pipe(
    R.sortBy(R.prop('age')), // sort user by the age property
    R.map(R.prop('name')), // get each name property
    R.join(', '), // join the names with a comma
  )(users)) // => "joe, chet"
}

env(
  sample1, 
  sample2, 
  sample3, 
  sample5,
  sample6,
  sample7,
)

View Compiled

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js