详解如何在JS代码中消灭for循环(2)

const unfold = (f, seed) => { const go = (f, seed, acc) => { const res = f(seed); return res ? go(f, res[1], acc.concat(res[0])) : acc; }; return go(f, seed, []); };

根据这个 unfold 函数,定义一个 Python 里面的 range 函数。

答案:

const range = (min, max, step = 1) => unfold(x => x < max && [x, x + step], min);

三,用递归代替迭代(可以break!)

Edit: 如何解决递归爆栈,可以参考我的另一篇文章《不懂递归?读完这篇保证你懂》

问题十四:

将两个数组每个元素一一对应相加。注意,第二个数组比第一个多出两个,不要把第二个数组遍历完。

const num1 = [3, 4, 5, 6, 7]; const num2 = [43, 23, 5, 67, 87, 3, 6];

答案:

const zipWith = f => xs => ys => { if (xs.length === 0 || ys.length === 0) return []; const [xHead, ...xTail] = xs; const [yHead, ...yTail] = ys; return [f(xHead)(yHead), ...zipWith(f)(xTail)(yTail)]; }; const add = x => y => x + y; zipWith(add)(num1)(num2);

问题十五:

将 Stark 家族成员提取出来。注意,目标数据在数组前面,使用 filter 方法遍历整个数组是浪费。

const houses = [ "Eddard Stark", "Catelyn Stark", "Rickard Stark", "Brandon Stark", "Rob Stark", "Sansa Stark", "Arya Stark", "Bran Stark", "Rickon Stark", "Lyanna Stark", "Tywin Lannister", "Cersei Lannister", "Jaime Lannister", "Tyrion Lannister", "Joffrey Baratheon" ];

答案:

const takeWhile = f => ([head, ...tail]) => f(head) ? [head, ...takeWhile(f)(tail)] : []; const isStark = name => name.toLowerCase().includes("stark"); takeWhile(isStark)(houses);

问题十六:

找出数组中的奇数,然后取出前4个:

const numList = [1, 3, 11, 4, 2, 5, 6, 7];

答案:

const takeFirst = (limit, f, arr) => { if (limit === 0 || arr.length === 0) return []; const [head, ...tail] = arr; return f(head) ? [head, ...takeFirst(limit - 1, f, tail)] : takeFirst(limit, f, tail); }; const isOdd = n => n % 2 === 1; takeFirst(4, isOdd, numList);

四,使用高阶函数遍历数组时可能遇到的陷阱

问题十七:

从长度为 100 万的随机整数组成的数组中取出偶数,再把所有数字乘以 3

// 用我们刚刚定义的辅助函数来生成符合要求的数组 const bigArr = genNumArr(1e6, 100);

能运行的答案:

const isEven = num => num % 2 === 0; const triple = num => num * 3; bigArr.filter(isEven).map(triple);

注意,上面的解决方案将数组遍历了两次,无疑是浪费。如果写 for 循环,只用遍历一次:

const results = []; for (let i = 0; i < bigArr.length; i++) { if (isEven(bigArr[i])) { results.push(triple(bigArr[i])); } }

在我的电脑上测试,先 filter 再 map 的方法耗时 105.024 ms,而采用 for 循环的方法耗时仅 25.598 ms!那是否说明遇到此类情况必须用 for 循环解决呢? No!

五,死磕到底,Transduce!

我们先用 reduce 来定义 filter 和 map,至于为什么这样做等下再解释。

const filter = (f, arr) => arr.reduce((acc, val) => (f(val) && acc.push(val), acc), []); const map = (f, arr) => arr.reduce((acc, val) => (acc.push(f(val)), acc), []);

重新定义的 filter 和 map 有共有的逻辑。我们把这部分共有的逻辑叫做 reducer。有了共有的逻辑后,我们可以进一步地抽象,把 reducer 抽离出来,然后传入 filter 和 map:

const filter = f => reducer => (acc, value) => { if (f(value)) return reducer(acc, value); return acc; }; const map = f => reducer => (acc, value) => reducer(acc, f(value));

现在 filter 和 map 的函数 signature 一样,我们就可以进行函数组合(function composition)了。

const pushReducer = (acc, value) => (acc.push(value), acc); bigNum.reduce(map(triple)(filter(isEven)(pushReducer)), []);

但是这样嵌套写法易读性太差,很容易出错。我们可以写一个工具函数来辅助函数组合:

const pipe = (...fns) => (...args) => fns.reduce((fx, fy) => fy(fx), ...args);

然后我们就可以优雅地组合函数了:

bigNum.reduce( pipe( filter(isEven), map(triple) )(pushReducer), [] );

经过测试(用 console.time()/console.timeEnd()),上面的写法耗时 33.898 ms,仅比 for 循环慢 8 ms。为了代码的易维护性和易读性,这点性能上的微小牺牲,我认为是可以接受的。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/771f86e4590a7942939ae05ee0e292a5.html