[Transducer] Make an Into Helper to Remove Boilerplate and Simplify our Transduce API
Our transduce
function is powerful but requires a lot of boilerplate. It would be nice if we had a way to transduce into arrays and objects without having to specify the inner reducer behaviour, i.e. how to build up values, since a given collection type will almost always have the same inner reducer.
In this lesson we'll being doing just that with an into()
helper function that will know if an array or object collection is passed in and handle each case accordingly.
The whole point to make 'into' helper is hide the inner reducer logic from user. So 'into' helper will check the target's type, based on the type, will use different inner reducer.
import {isPlainObject, isNumber} from 'lodash'; import {compose, map, filter, pushReducer} from '../utils'; //current transduce const transduce = (xf /** could be composed **/, reducer, seed, collection) => { const transformedReducer = xf(reducer); let accumulation = seed; for (let value of collection) { accumulation = transformedReducer(accumulation, value); } return accumulation; }; const objectReducer = (obj, value) => Object.assign(obj, value); const into = (to, xf, collection) => { if (Array.isArray(to)) return transduce(xf, pushReducer, to, collection); else if (isPlainObject(to)) return transduce(xf, objectReducer, to, collection); throw new Error('into only supports arrays and objects as `to`'); }; into( [], compose( map(x => x/2), map(x => x * 10) ), [1,2,3,4], ); into( {}, compose(filter(isNumber), map(val => ({[val]: val}))), [1,2,3,4, 'hello', () => 'world'], );
utils:
export const compose = (...functions) => functions.reduce((accumulation, fn) => (...args) => accumulation(fn(...args)), x => x); export const map = xf => reducer => { return (accumulation, value) => { return reducer(accumulation, xf(value)); }; }; export const filter = predicate => reducer => { return (accumulation, value) => { if (predicate(value)) return reducer(accumulation, value); return accumulation; }; }; export const pushReducer = (accumulation, value) => { accumulation.push(value); return accumulation; };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-01-17 [Angular Directive] Structure directive and <template>
2017-01-17 [React] Break up components into smaller pieces using Functional Components
2017-01-17 [TypeScript] Simplify asynchronous callback functions using async/await