兩個函數(shù)的組合
const compose = (a , b) => c => a( b( c ) );
栗子:統(tǒng)計單詞個數(shù)
分兩步:
1勺爱、獲取空格
2救巷、獲取長度
const splitIntoSpaces = str => str.split(' ');
const len = arr => arr.length;
const word = compose(len , splint); // 注意順序
word('saf dfadsf dfadf adfasdf'); // 輸出4
強調(diào)注意順序绿渣,不知道為什么的可以分別打印splitIntoSpaces 的str和len的arr就知道了
多個函數(shù)的組合
const reduce = (arr: Array<any>, fn, value) => {
arr.map(r => (value= fn(value, r)));
return value;
};
const composeN = (...fns) => value =>reduce(fns.reverse(), (acc, fn) => fn(acc), value);
const splint = str => str.split(' ');
const len = arr => arr.length;
const word = composeN(len, splint); // 注意順序
const d = word('saf dfadsf dfadf adfasdf'); // 4