[Transducer] Create a Sequence Helper to Transduce Without Changing Collection Types

A frequent use case when transducing is to apply a transformation to items without changing the type of the collection.

In this lesson, we'll create a helper to do just that. seq will be similar to into, except the target type will be inferred from the source collection. For example, if transducing from an array, seq will create an array as the output collection as well.

seq is thus more restrictive and easier to consume than into.

 

The whole for 'seq' is we don't need to worry about collection type will different from target type. In short, input and output are the same type.

 

复制代码
import {isPlainObject} from 'lodash';
import {compose, map, arrayReducer, objectReducer, transduce} from '../utils.js';

const into = (to, xf, collection) => {
  if (Array.isArray(to)) return transduce(xf, arrayReducer, to, collection);
  else if (isPlainObject(to)) return transduce(xf, objectReducer, to, collection);
  throw new Error('into only supports arrays and objects as `to`');
};

const seq = (xf, collection) => {
  if (Array.isArray(collection)) return transduce(xf, arrayReducer, [], collection);
  else if (isPlainObject(collection)) return transduce(xf, objectReducer, {}, collection);
  throw new Error('unsupported collection type');
};

seq(map(x => x*2), [1,2,3]);

const flip = compose(
  map(([k,v]) => ({[v*10]:k})),
);

seq(flip, {one: 1, two: 2, three: 3});
复制代码

 

posted @   Zhentiw  阅读(223)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示