[Transducer] Transduce When the Collection Type is an Object

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Transducer] Transduce When the Collection Type is an Object相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

Reduce 和 Transduce 的含义

[Transducer] Step by Step to build a simple transducer

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

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

为啥 OpenFST 似乎没有“运行”或“接受”或“转导”命令?

天线信号的接收流程