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

2021-07-01 17:07

阅读:1175

标签:rip   func   array   ini   UNC   com   reducer   fun   reduce   

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

标签:rip   func   array   ini   UNC   com   reducer   fun   reduce   

原文地址:https://www.cnblogs.com/Answer1215/p/9636262.html


评论


亲,登录后才可以留言!