JS functional programming

1. Why learn functional programming

1. With the popularity of react, functional programming has attracted more and more attention
2.Vue3 also began to use functional programming
3. Functional programming can abandon this
4. In the packaging process, we can better use tree shanking to filter useless code
5. Facilitate testing, make the code more flexible and reuse functions
6. Many libraries help us with functional development, lodash, Randa, etc

2. What is functional programming

Function programming (FP) FP is one of the programming paradigms

  • Thinking mode of object-oriented programming: abstract things in the real world into classes and objects in the program world, and demonstrate the relationship between things through encapsulation, inheritance and polymorphism
  • Thinking mode of functional programming: abstracting things in the real world and the relationship between things into the program world
	// Non functional formula
	let num1 = 1
	let num2 = 2
	let sum = num1 + num2
	console.log(sum)
	
	// Functional formula
	function add (n1, n2) {
		return n1 + n2
	}
	let sum = add(1, 2)
	console.log(sum)

3. Function is a first-class citizen

  • Functions can be stored in variables
  • Functions can be used as arguments
  • Functions can be used as return values
	// 1. Function as variable**
		let fn = function() {
			console.log('Hello')
		}
		let obj = {
			fn: views.fn
		}
	
	// 2. Function as parameter**
		let arr = [1, 2, 3, 4, 5]
		
		// Case 1
		function forEach(arr, fn) {
			for (let i = 0; i < arr.length; i++) {
				fn(arr[i])
			}
		}
		forEach(arr, function(item) {
			console.log(item) // 1, 2, 3, 4, 5
		})
		
		// Case 2
		function filter(arr, fn) {
			let result = []
			for (let i = 0; i < arr.length; i++) {
				if (fn(arr[i])) result.push(arr[i])
			}
			return result
		}
		let results = filter(arr, (item) => {
			return item % 2 === 0
		})
		console.log(results) // [2, 4]

	// 3. Function as return value**
		function once(fn) {
			let done = false
			return function() {
				if(!done) {
					done = true
					return fn.apply(this, arguments)
				}
			}
		}
		let run = once(() => {
			console.log('Execute only once')
		})
		run()
		run()
		run()

4. Significance of higher-order function

  • The code is concise and flexible
  • Can help us shield the details of implementation

5. Common high-order functions

  • forEach
  • map
  • filter
  • every
  • some
  • ...

6. Closure

  • Functions are nested functions. Internal functions can access the parameters and variables of external functions
  • Closures can extend the scope of internal variables of external functions
  • When the internal function is not called, the memory will not be released, resulting in garbage
	function checkAge(min) {
		return function(age) {
			return min >= age
		}
	}

7. Pure function

  • The same input always gets the same output

  • Advantages:
    1. The value can be cached
    2. Make testing more convenient (e.g. the result of unit test assertion function)
    3. Parallel processing parallel operation of shared data in a multithreaded environment (es6 (web worker) can enable multithreading)

  • side effect:
    If the function depends on the external state, the output cannot be guaranteed to be the same

    let mini = 18 
    function (age) {
    	return age >= mini
    }
    age(20) => true
    
    let mini = 21
    age(20) => false
    
// Pure function / impure function
	// Pure function
	let array = [1, 2, 3, 4, 5]
	array.slice(0, 3) ⇒ [1, 2, 3]
	array.slice(0, 3) ⇒ [1, 2, 3]
	array.slice(0, 3) ⇒ [1, 2, 3]
	
	// Impure function
	array.splice(0, 3) ⇒  [1, 2, 3]
	array.splice(0, 3) ⇒  [4, 5, ]
	array.splice(0, 3) ⇒  []

	// Pure function
	function getSum(n1, n2) {
		return n1 + n2
	}
	getSum(1, 2) => 3
	getSum(1, 2) => 3
	getSum(1, 2) => 3
	getSum(1, 2) => 3

8. * function coritization

  • When a function has multiple parameters, it only receives some parameters and returns a new function to receive the remaining parameters (convert a multivariate function into a unary function)
  • Parameters can be cached
	// demonstration
	// function checkAge(age) {/ / hard coded
	//	 let min = 18
	//	 return age >= min
	// }
	
	// Ordinary pure function
	// function checkAge(min, age) {
	//	return age >= min
	// }
	// console.log(checkAge(18, 20))
	// console.log(checkAge(18, 24))
	// console.log(checkAge(22, 24))
	
	// Function coritization
	function checkAge(min) {
		return function(age) {
			return age >= min
		}
	}
	// es6 arrow function
	let checkAge = min => (age => age >= min)
	
	let checkAge18 = checkAge(18)
	let checkAge20 = checkAge(20)
    checkAge18(20)
    checkAge20(22)
	
	// lodash Coriolis principle
	function getSum(a, b, c) {
		return a + b + c
	}
	function curry(func) {
		return function curryFn(...args) {
			// Determine the number of arguments and formal parameters

			// Argument < formal parameter
			if (args.length < func.length) {
				return function() {
					return curryFn(...args.concat(Array.from(arguments)))
				}
			}
			// The actual parameter is greater than or equal to the formal parameter
			return func(...args)
		}
	}
	curry(getSum(1, 2, 3)) // 6
	curry(getSum(1)(2, 3)) // 6
	curry(getSum(1)(2)(3)) // 6

9. Function combination (function combination is executed from right to left by default)

  • If a function needs to be processed by multiple functions to get the final value, the intermediate processes can be combined into one function at this time
  • Function composition allows us to regroup fine-grained functions into new functions
	function compose(fn1, fn2) {
		return function(value) {
			return fn1(fn2(value))
		}
	}
	
	// Gets the last element of the array
	function reverse(array) {
		return array.reverse()
	}
	function first(array) {
		return array[0]
	}
	const last = compose(first, reverse)
	last([1, 2, 3, 4]) => 4

Keywords: Javascript Front-end

Added by Holoverse on Tue, 01 Mar 2022 04:17:48 +0200