[Javascript] Flattening nested arrays: a little exercise in functional refactoring
2024-09-08 05:22:04
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 = [, [, ], [[, [, [], ], [, ]]]]; 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]
最新文章
- D3.js学习(四)
- 【翻译】ASP.NET MVC 5属性路由(转)
- Notes of 大数据智能
- Hosts知多少?
- mac系统安装php redis扩展
- win10系统的点评
- HttpClient入门
- jar包问题
- 一份关于jvm内存调优及原理的学习笔记
- jQuery中操作Ajax方法小结
- 采用Opserver来监控你的ASP.NET项目系列(三、监控你的服务器状态)
- Android开发之组件
- P3396 哈希冲突
- 解决Git Revert操作后再次Merge代码被冲掉的问题
- Linux网络编程学习(五) ----- 信号(第四章)
- rt-thread learning notes
- 15款css3鼠标悬停图片动画过渡特效
- python操作Excel读写(使用xlrd和xlrt)
- python文件操作,读取,修改,合并
- beat冲刺(3/7)
热门文章
- Python_高阶函数、装饰器(decorator)
- Linux关于文件的权限笔记
- TensorFlow低阶API(一)—— 简介
- netstat -a 显示出你的计算机当前所开放的所有端口
- json 存 window.localStorage.setItem('hideColums',hideArr);
- Zend Studio / Eclipse 缩进设置
- ubuntulinux 更改时区设置时间
- GPS坐标转化距离(短距离模型公式)
- Spring Boot . 4 -- 定制 Spring Boot 配置 【2】
- 浅谈FFT(快速博立叶变换)&;学习笔记