[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]

 

posted @ 2018-09-12 17:43  Zhentiw  阅读(145)  评论(0编辑  收藏  举报