zoukankan      html  css  js  c++  java
  • [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});
  • 相关阅读:
    VS2010中添加MVC3和MVC4
    C#--对象转成XML的方法
    Web优化的措施
    Socket的使用(简单测试)
    WCF、WebAPI、WCFREST、WebService之间的区别
    Java和C#(笔记)
    各种窗口最小化快捷键详解
    SASS的安装及使用(前提:安装Ruby)
    查看Linux是32位还是64位
    log4j输出日志到文件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8305920.html
Copyright © 2011-2022 走看看