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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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});

 

以上是关于[Transducer] Create a Sequence Helper to Transduce Without Changing Collection Types的主要内容,如果未能解决你的问题,请参考以下文章

A Go library implementing an FST (finite state transducer)——mark下

problem during schema create,statement create sequence act_evt_log_seq

[Transducer + Ramda] Write highly performance / functional code by using transducer-js and ramda.js

[Transducer] Transduce When the Collection Type is an Object

Mybatis 插入操作时获取主键 (Oracle 触发器与SEQ)

todo:proc_create