[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});

 

转载于:https://www.cnblogs.com/Answer1215/p/8305920.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值