DEV Community

Cover image for A very simple introduction to Functional Programming
sigfried
sigfried

Posted on

4 2

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.

Top comments (1)

Collapse
 
tunaxor profile image
Angel Daniel Munoz Gonzalez

This is what FP is all about, you define the steps you need in order to achieve something

💯💯💯

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay