Functional Programming

Principles

  • Separate data from behavior

  • Use of declarative functions (as opposed to imperative)

  • Proper use of caching (computing efficiency)

  • Pure functions

  • Composing (chained atomic pure operations)

Pure functions

  • Don't mutate state (global scope)

  • Always have a return statement. This is useful for chaining purposes

  • Idempotence. On the same input, return the same output, regardless of how many times executed

  • Usually have 1 argument

//Side effects:
const array = [1,2,3];
function mutateArray(arr) {
  arr.pop()
}
function mutateArray2(arr) {
  arr.forEach(item => arr.push(1
  ))
}
//The order of the function calls will matter.
mutateArray(array)
mutateArray2(array)
array

Cache in memory

Here is a better implementation of caching, making the above pure.

Currying and Composing

Currying in JavaScript transforms a function that takes multiple arguments into a sequence of functions, each taking a single argument. For example, a function f(a, b) becomes f(a)(b). It allows partial application of functions, where you can fix some arguments and pass others later, enabling more flexible function usage.

pipe() and compose()

Composing is the process of chaining functions. In other words, through pipe() and compose() we create a pipeline of functions with the output of one function connected to the input of the next. This is the reason for which these functions need to be pure.

Instead of jamming functions within functions or creating a bunch of intermediate variables, let’s pipe all the things!

compose() is similar, it just deals with the chain in the opposite direction (from right to left).

Last updated

Was this helpful?