Learning notes

1. Functional programming abstracts the operation process, which can be understood as a mathematical formula such as y = sin(x)

2. Functions are also objects and can be treated like values, either as arguments or as return values

3. Higher-order functions: the function as a parameter or as a function of the return value sense: the higher-order functions can abstract general problem, just call later can (can not pay attention to the internal implementation details, need to focus on the goal), for example, the same circular array, higher-order functions do not need to use every time for each traversal, just call the wrapper function:

  1. Process oriented approach:
let arr = [1.2.3.4];
for (i=0; i<arr.length; i++) {console.log(arr[i])
}
Copy the code
  1. Using higher-order functions:
// Higher-order functions - functions as arguments
function forEach (array, fn) {
  for (let i = 0; i < array.length; i++) {
    fn(array[i])
  }
}
/ / test
let arr = [1.3.4.7.8]
forEach(arr, function (item) {
   console.log(item)
})

// filter
function filter (array, fn) {
  let results = []
  for (let i = 0; i < array.length; i++) {
    if (fn(array[i])) {
      results.push(array[i])
    }
  }
  return results
}
/ / test
let arr = [1.3.4.7.8]
let r = filter(arr, function (item) {
  return item % 2= = =0
})
console.log(r)

Copy the code

Commonly used higher-order functions: map every some

// map
const map = (array, fn) = > {
  let results = []
  for (let value of array) {
    results.push(fn(value))
  }
  return results
}
/ / test
// let arr = [1, 2, 3, 4]
// arr = map(arr, v => v * v)
// console.log(arr)

// every
const every = (array, fn) = > {
  let result = true
  for (let value of array) {
    result = fn(value)
    if(! result) {break}}return result
}
/ / test
// let arr = [9, 12, 14]
// let r = every(arr, v => v > 10)
// console.log(r)

// some
const some = (array, fn) = > {
  let result = false
  for (let value of array) {
    result = fn(value)
    if (result) {
      break}}return result
}
/ / test
let arr = [1.3.5.9]
let r = some(arr, v= > v % 2= = =0)
console.log(r)
Copy the code