Skip to content

Functional programming

  • more natural and declarive, focus on why and what outcome
  • code become more maintainable
  • easier to be understood and read

side effect

  • console.log
  • database storage
  • network call
  • dom
  • timestamps
  • random number

How to minimize the side effect? make it obvious otherwise

Pure Function

without side effect don't have outside dependencies input need to be static, const(can't be objects) Extract Impurity

reduce surface

use a (a function return a function) to pass parameters, 控制不变的能力加强了

Equational Reasoning

if 2 functions have same arguments, then it could be combined into same shape

memorization

use memorize

Referential Transparency

Canonical defination:

if the function call could be replaced by the result and have no impact overall, that's pure function

From general to speical

  • parameters order
  • relationship of funciton and content

changing shape

like functions have different count of input and output

composition

It could combine those functions into a new abstract one.

Immutability

  • assignment
  • pass varible as parameters to funciton
  • Value Immutability
  • read only
    • Object.freeze()
  • assume the parameter is read only
    • make a copy of it
  • Immutable data structure
  • natively optimized: store the diff when create a copy

Recursion

  • find the init condition and subproblem

Tail call

  • have reference with current stack

Proper Tail Call

  • use strict
  • return a single fucntion call

Trampolines

Like a bounce, it only store data in one stack

Convert tail call to trampolines

wrap the return function to a new function and return it

9kQWb4pnAJqCeou

Map - transformation

one input(function), one output(collection of data)

Reducer

An implement of composition

  • Take a function, and a init value, one output(collection of data)
  • function's parameters:
    • accumulator
    • current value

Transduction

composition of reductions