码迷,mamicode.com
首页 > 其他好文 > 详细

[Transducer] Transduce When the Collection Type is an Object

时间:2018-01-17 21:59:13      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:can   support   use   loop   reduce   sed   nsf   could   point   

We‘ve seen how we can transduce from arrays or other iterables, but plain objects aren‘t iterable in Javascript. In this lesson we‘ll modify our transduce() function so that it supports iterating from plain objects as well, treating each key value pair as an entry in the collection.

To do this we‘ll be using a lodash function called entries.

 

The whole point to make collection works for Object type is because when we use for.. of loop, Object is not itertable type, so Object still cannot be used. The fix that problem, we can use ‘entries‘ from lodash, to only get value as an array from the Object, so that we can loop though the array.

 

import {isPlainObject, entries} from ‘lodash‘;
import {map, into} from ‘../utils‘;

let transduce = (xf /** could be composed **/, reducer, seed, _collection) => {

    const transformedReducer = xf(reducer);
    let accumulation = seed;

    const collection = isPlainObject(_collection) ? entries(_collection) : _collection;

    for (let value of collection) {
        accumulation = transformedReducer(accumulation, value);
    }

    return accumulation;
};

const objectValues = obj => {
    return into([], map(kv => kv[1]), obj);
};

objectValues({one: 1, two: 2});

 

[Transducer] Transduce When the Collection Type is an Object

标签:can   support   use   loop   reduce   sed   nsf   could   point   

原文地址:https://www.cnblogs.com/Answer1215/p/8305883.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!