Repozytorium Web Developera

Archiwum z lat 2013-2018, treści mogą być nieaktualne.

JavaScript - Functional Programming

Functional Programming

Useful links

Terms

  • - pure and impure functions
  • - immutable data structures
  • - currying
  • - partial application
  • - advanced: monad, functor, applicative, endomorphism

Notes

  • - pure functions do not use global state, do not have side effects, always return the same output for the same input
  • - Higher Order Functions accepts a function as an argument and/or returns a function
  • - HOF can use closures, so a function returns a function where the latter has access also to the scope/variables of the first function
  • - FP promotes immutability
  • - currying is actually creating a function that returns a function so these functions accept only one argument `add(x, y) === add(x)(y)`
  • - currying is the act of refactoring a function so that it receives its arguments one at a time
  • - a higher order function `compose()` takes all of the functions we want to combine, and returns us a new function to use in our app `compose(scream, repeat)(x) === scream(repeat(x))`
  • - partial application occurs whenever a curried function has some but not all of its function applied `add(2)(y) === add2(y)`
  • - pointfree programming is passing a named function as an argument to avoid writing an anonymous function with interim variables instead - Pointfree programming increases code legibility, decreases the surface area for bugs, and makes our code more composable and unit testable `arr.map(double)` instead of `arr.map(x => x * 2)`
  • - function composition means that you can make a one function from two other functions
  • - composition is like add operation `1+2+3 === 1+(2+3)`
  • - compose function often follows mathematical order, so `compose(a, b)(x)` is like `a(b(x))`
  • - pure functions are referentially transparent, they allow for a bunch of optimization techniques such as memoization (which is used to speed up repeated evaluations by caching function results)
  • - Immutable data is also thread-safe and failure atomic
  • - FP is more declarative, where declarative pattern puts the focus on the problem domain and not the implementation details. It typically leads to a much more concise and much less error-prone code. In addition, it is much easier to read and reason about.

What is purity

  • - its return value is only determined by its input values
  • - its return value is always the same for the same input values
  • - don't use global state or modify it
  • - have no side effects
  • - a React component can be considered pure if it renders the same output for the same state and props

Why FP?

  • - easier testing and debugging