React-redux之compose

compose 源碼

先來看一下compose的源碼官網源碼

/**
 * Composes single-argument functions from right to left. The rightmost
 * function can take multiple arguments as it provides the signature for
 * the resulting composite function.
 *
 * @param {...Function} funcs The functions to compose.
 * @returns {Function} A function obtained by composing the argument functions
 * from right to left. For example, compose(f, g, h) is identical to doing
 * (...args) => f(g(h(...args))).
 */

export default function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg
  }

  if (funcs.length === 1) {
    return funcs[0]
  }

  return funcs.reduce((a, b) => (...args) => a(b(...args)))
}

從這裏我們知道實際上調用的數組的reduce方法;

在理解compose函數之前先來認識下什麼是reduce方法?

reduce 方法

  1. 官網案例

reduce() 方法對數組中的每個元素執行一個由您提供的reducer函數(升序執行),將其結果彙總爲單個返回值。

  1. 語法

arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

  1. 參數
  • callback
    執行數組中每個值 (如果沒有提供 initialValue則第一個值除外)的函數,包含四個參數:
    • accumulator
      累計器累計回調的返回值; 它是上一次調用回調時返回的累積值,或initialValue(見於下方)。
    • currentValue
      數組中正在處理的元素。
    • index 可選
      數組中正在處理的當前元素的索引。 如果提供了initialValue,則起始索引號爲0,否則從索引1起始。
    • array可選
      調用reduce()的數組
  • initialValue可選
    作爲第一次調用 callback函數時的第一個參數的值。 如果沒有提供初始值,則將使用數組中的第一個元素。 在沒有初始值的空數組上調用 reduce 將報錯。
  1. 案例
  • 累計求和
var sum = [0, 1, 2, 3].reduce(function (a, b) {
  return a + b;
}, 0);
// sum 值爲 6

存在一個數組 ,元素項爲: 0,1,2,3,初始值爲0;其中a參數爲accumulator,也就是累計值的變量;最後的0;表示initialValue;

  • 字符計數
	var series = ['a1', 'a3', 'a1', 'a5',  'a7', 'a1', 'a3', 'a4', 'a2', 'a1'];

	var result = series.reduce(function(accumulator,currentValue){
		if(currentValue in accumulator){
			accumulator[currentValue]++;
		}else{
			accumulator[currentValue] = 1;
		}
		return accumulator;
	},{})
	
	console.log(JSON.stringify(result));
	
// {"a1":4,"a3":2,"a5":1,"a7":1,"a4":1,"a2":1}

compose 函數

  1. 案例
import { compose } 'redux'// function f
const f1 = (arg) => `函數f(${arg})` 

// function g
const g2 = (arg) => `函數g(${arg})`

// function h 最後一個函數可以接受多個參數
const h3 = (...arg) => `函數h(${arg.join('_')})`

console.log(compose(f1,g2,h3)('a', 'b', 'c')) //函數f1(函數g2(函數h3(a_b_c)))

  1. 總結:compose函數最終會返回以最後的參數爲最後一個函數的參數項依次累加函數。調用方法依次從最裏面的參數到最外面的參數依次調用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章