Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Transforming a Javascript iterable into an array

I'm trying to use the new Map object from Javascript EC6, since it's already supported in the latest Firefox and Chrome versions.

But I'm finding it very limited in "functional" programming, because it lacks classic map, filter etc. methods that would work nicely with a [key, value] pair. It has a forEach but that does NOT returns the callback result.

If I could transform its map.entries() from a MapIterator into a simple Array I could then use the standard .map, .filter with no additional hacks.

Is there a "good" way to transform a Javascript Iterator into an Array? In python it's as easy as doing list(iterator)... but Array(m.entries()) return an array with the Iterator as its first element!!!

EDIT

I forgot to specify I'm looking for an answer which works wherever Map works, which means at least Chrome and Firefox (Array.from does not work in Chrome).

PS.

I know there's the fantastic wu.js but its dependency on traceur puts me off...

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are looking for the new Array.from function which converts arbitrary iterables to array instances:

var arr = Array.from(map.entries());

It is now supported in Edge, FF, Chrome and Node 4+.

Of course, it might be worth to define map, filter and similar methods directly on the iterator interface, so that you can avoid allocating the array. You also might want to use a generator function instead of higher-order functions:

function* map(iterable) {
    var i = 0;
    for (var item of iterable)
        yield yourTransformation(item, i++);
}
function* filter(iterable) {
    var i = 0;
    for (var item of iterable)
        if (yourPredicate(item, i++))
             yield item;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...