[Javascript] Flattening nested arrays: a little exercise in functional refactoring

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Javascript] Flattening nested arrays: a little exercise in functional refactoring相关的知识,希望对你有一定的参考价值。

In this lesson we write an imperative function to flatten nested arrays, and then use the popular map, reduce, compose, and pipe functions to transform it into a high-level, point-free, functional implementation.

 

const array = [1, [2, 3], [[4, [5, [6], 7], [8, 9]]]];

const concatReducer = (acc, curr) => acc.concat(curr);
const map = f => ary => ary.map(f);
const reduce = (f, init) => ary => ary.reduce(f, init);
const compose = (f, g) => x => f(g(x));

const flatten1Element = x => (Array.isArray(x) ? flatten(x) : x);
const flattenEachElement = map(flatten1Element);
const flattenOneLevel = reduce(concatReducer, []);

const flatten = compose(
  flattenOneLevel,
  flattenEachElement
);

console.log(flatten(array));
//[1,2,3,4,5,6,7,8,9]

 

以上是关于[Javascript] Flattening nested arrays: a little exercise in functional refactoring的主要内容,如果未能解决你的问题,请参考以下文章

java Flattening.java

JavaSript数组扁平化去重

“展平”单元阵列

ReactiveSwift中平面图策略之间的差异

[RxJS] Utility operator: do

13.1JSON