Using map() on an iterator

后端 未结 8 1801
误落风尘
误落风尘 2021-02-01 11:59

Say we have a Map: let m = new Map();, using m.values() returns a map iterator.

But I can\'t use forEach() or map() o

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 12:20

    You could define another iterator function to loop over this:

    function* generator() {
        for (let i = 0; i < 10; i++) {
            console.log(i);
            yield i;
        }
    }
    
    function* mapIterator(iterator, mapping) {
        for (let i of iterator) {
            yield mapping(i);
        }
    }
    
    let values = generator();
    let mapped = mapIterator(values, (i) => {
        let result = i*2;
        console.log(`x2 = ${result}`);
        return result;
    });
    
    console.log('The values will be generated right now.');
    console.log(Array.from(mapped).join(','));

    Now you might ask: why not just use Array.from instead? Because this will run through the entire iterator, save it to a (temporary) array, iterate it again and then do the mapping. If the list is huge (or even potentially infinite) this will lead to unnecessary memory usage.

    Of course, if the list of items is fairly small, using Array.from should be more than sufficient.

提交回复
热议问题