码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-12 19:56:27      阅读:183      评论:0      收藏:0      [点我收藏+]

标签: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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!