zoukankan      html  css  js  c++  java
  • [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;
    };
  • 相关阅读:
    第十六届全国大学智能汽车竞赛竞速比赛规则-讨论稿
    从0到1设计一台8bit计算机
    在 CentOS7 上安装 MongoDB
    sea.js五分钟上手
    自动调试自动编译五分钟上手
    自动调试自动编译五分钟上手
    在react底下安装环境
    在react底下安装环境
    推荐几款好用的云笔记软件
    推荐几款好用的云笔记软件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8305758.html
Copyright © 2011-2022 走看看