Skip to content

Functional programming

RobinFrugte97 edited this page Nov 15, 2019 · 2 revisions

Functional programming

Functional programming is all about creating short, functional and reusable code. The goal is to have your code be made up of seperate functions. If your code is functional enough, you can even seperate functions in modules for easy reuseability.

Fun Fun Function

To get a better understanding of functional programming I am going to follow the Youtube video series of Fun Fun Function

Video 1: Higher-order functions

Why functional programming?

  • Less bugs -- Easier to reason about
  • Less time -- Reuse more code

Higher order function

  • Composition -- Allows you to write smaller functions to use in a bigger function

Example: Filter

  • Array method that accepts another function
  • Callback functions. Function that is called back by the host function for each item in the array for example.
  • Filter is shorter than a traditional for-loop.
  • You can reuse a well writen callback function. For example if you have a function that returns all prints that come from Japan out of an array of prints from all over the world, you can then use that callback function with a filter function to filter all Japanese prints. You can use the same callback function with a reject function to reject all Japanese prints.

This video in short, divide your code in small simple functions and compose them together in higher order functions.

Video 2: Map

Example: Map

  • Another method on an array.
  • var location = prints.map(function(print){ return print.location })
  • Much shorter than writing a for loop.
  • Can be even shorter with ES6.
  • let location = prints.map((print) => print.location)

This video in short, more emphasis on how short functional programming is. It is so much easier to understand. Writing functional programming in ES6 is even shorter.

Video 3 & 4: Reduce

  • Super list transformation. -- You can use all the afforementioned methods.

  • Takes a callback function

  • But also needs an object, for example a starting point for a sum.

  • trim() to remove line breaks at the start and end of a string.

  • Good functional code is made up of small functions that do one thing. You bind those functions together. Chaining, callback functions etc.

Video 8: Promises

  • Promises are more powerful than callbacks.
  • Promises can resolve or reject.
  • Promises can be resolved using asynchronous functions and awaiting the promise result. You can also use .then() to create a chain of what to do with the promise result.