[Javascript] Transduce over any Iteratable Collection
So far we've been transducing by manually calling .reduce()
on arrays, but we want to be able to transduce over other collection types as well.
In this lesson we'll create a transduce
function to support transducing over any data structure that implements the es2015 iterable protocol. We’ll put it to the test by transducing over strings and maps, as well as going from one collection type as input to another as output.
The whole point to make transducer work for all iteratable collection is that, iteratable collction can be Map, TypedArray, Array, Set and String.
Current the implement from last post:
[1, 2, 3, 4].reduce( compose(isNot2Filter, isEvenFilter, doubleMap)(pushReducer), [], ); const transduce = (xf, reducer, seed, collection) => { collection.reduce(xf(reducer), seed) }
This implementaion only works for Array type.
If we want Transducer can be used for all Itertable type, we need to change by using 'reduce' to 'for...of' loop.
const transduce = (xf, reducer, seed, collection) => { const transformedReducer = xf(reducer); let accumulation = seed; for (const value of collection) { accumulation = transformedReducer(accumulation, value); } return accumulation; }
Now that, we can use for any iteratable collection not only Array type:
const toUpper = str => str.toUpperCase(); const isVowel = char => ['a', 'e', 'i', 'o', 'u', 'y'].includes(char.toLowerCase()); transduce( compose(map(toUpper), filter(isVowel)), (str, char) => str + char, '', 'adrian', ); const numMap = new Map(); numMap.set('a', 1); numMap.set('b', 2); numMap.set('c', 3); numMap.set('d', 4); transduce( compose(isNot2Filter, isEvenFilter, doubleMap), pushReducer, [], numMap.values(), );
相关文章
- javascript 高级教程 视频_精通JavaScript
- Javascript中作用域的理解?
- JavaScript事件流
- 网站中引入了多个版本的 JavaScript 库防止对象冲突的方法 - 在线客服系统源码
- 用JavaScript将数字转换为大写金额详解编程语言
- JavaScript学习总结(十七)——Javascript原型链的原理详解编程语言
- 解读MySQL中ANY关键字的含义(mysql中any含义)
- 任意MySQL 中 Any 的作用(any 的作用mysql)
- 任意一个解决方案Oracle Any函数搭配(oracle any函数)
- JavaScript获得选中文本内容的方法
- javascript面向对象编程基础:封装
- 用Javascript验证表单(form)中多选框(checkbox)值
- javaScript同意等待代码实现心得
- JavaScript布尔操作符解析&&||!
- Javascript加载速度慢的解决方案
- JavaScript实现班级随机点名小应用需求的具体分析
- Javascript核心读书有感之语言核心