A very simple introduction to Functional Programming

sigfriedcub1990

sigfried

Posted on August 24, 2021

A very simple introduction to Functional Programming

If you’ve heard the "buzzwords" Functional Programming (FP), composition, point free, etc, and you were completely lost… you’re NOT alone. Here’s a sneak peak of the things you can do if you compose things and follow a functional and point free style of programming.

const _ = require('lodash/fp')

const lines = [
  {
    name: "We're the eggmen",
    order: 2,
  },
  {
    name: "I'm the eggman",
    order: 1
  },
  {
    name: "I'm the walrus",
    order: 3
  }
]

function main(lines) {
  // generateSelectObject :: Object -> Object
  const generateSelectObject = ({ name, order }) => ({
    value: `${name}_${order},
    label: name,
  })

  const sortAndMapLines = _.compose(
    _.map(generateSelectObject),
    _.sortBy(['order'])
  )

  const orderedLines = sortAndMapLines(lines)

  orderedLines.unshift({
    label: 'All lines',
    value: 'All lines'
  })

  return orderedLines
}

const res = main(lines)
console.log(res)
Enter fullscreen mode Exit fullscreen mode

I’ll argue that the most interesting part of this boring code is this one:

const sortAndMapLines = _.compose(
  _.map(generateSelectObject),
  _.sortBy(['order'])
)
Enter fullscreen mode Exit fullscreen mode

This is what FP is all about, you define the steps you need in order to achieve something, in this case the sorted and then mapped results of lines. Notice we’re composing two functions there, the sort and the map from Lodash and it’s point free because neither function declares explicitly with what data they will work with.

Hopefully this rambling is helpful and it will whet your appetite to search for better ways to do your work and improve the overall quality of our code. A very good place to start with is Prof. Frisby's Mostly Adequate Guide to Functional Programming which I very much recommend.

💖 💪 🙅 🚩
sigfriedcub1990
sigfried

Posted on August 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related