Functional coding paradigm

Why should I learn functional programming

  • Functional programming is getting more attention with the popularity of React
  • Vue3 is also embracing functional programming
  • Functional programming can discard this
  • The packaging process makes better use of Tree Shaking to filter out unwanted code
  • Convenient testing, convenient parallel processing
  • There are many libraries that can help us with functional development: Lodash, underscore, Ramdo

What is functional programming

  • Functional programming is like a mapping in mathematics like x= sine of x
  • (pure function) The same input always has the same result
  • There are inputs and outputs and the same inputs have to have the same outputs

Functions are first-class citizens

MDN First-class Function

  • Functions can be stored in variables
  • Function as a parameter
  • Function as the return value

In javascript, a function is just a normal object

Higher-order functions

What is a higher order function
  • Higher-order functions

    • You can pass a function as an argument to another function
    • You can treat a function as the return value of another function
  • Function as a parameter

function forEach(array,fn){ for(let i=0; i<array.length; Let arr=[1,2] function fn(item){console.log(item)} console.log(forEach(arr,fn))Copy the code
  • Function as the return value
function once(fn){ let done=false; if(! done){ done= true; Return fn. Apply (this,arguments)}} let sleep=once(function(lazy){console.log(' sleep ${lazy} sleep ')}) sleep(2) sleep(2)Copy the code
Meaning of using higher-order functions
  • Abstractions can help us block out the details and focus only on our results (goals)
  • Higher-order functions are used to abstract general purpose problems

For example,

Filter splice forEach we just need to know what the return result is so we don’t have to worry about the internals how do we do that

Commonly used high-level functions

  • forEach
  • map
  • filter
  • every
  • some
  • find/findIndex
  • reduce
  • sort
  • reverse
Const maMap=(array,fn)=>{let result=[]; for(let i=0; i<array.length; i++){ result.push(fn(array[i])) } return result; }; Let arr = [1, 2, 3, 4, 5]; arr=myMap(arr,(item)=>item*2)Copy the code

closure

  • Closure: A function is bundled with a reference to its surrounding state (lexical environment) to form a Closure.

    • It’s basically a function inside of another function
    • You can call a function inside another function from one scope and access members of that function’s scope.
function add(){ let sum=3; Return function(){console.log(sum)}} const fn=add(); return function(){console.log(sum)}} fn()Copy the code
  • The nature of closures: functions are placed on an execution stack when they are executed, and removed from the stack when they are finished. However, scope members on the stack can still be accessed by internal members because they cannot be freed by external references.

\