Lazy range iteration in javascript using underscore
I've caught myself using this in p开发者_运维知识库lace of a traditional for loop:
_.each(_.range(count), function(i){
...
});
The disadvantage being creating an unnecessary array of size count.
Still, i prefer the semantics of, for example, .each(.range(10,0,-1), ...); when iterating backwards.
Is there any way to do a lazy iteration over range, as with pythons xrange?
Just a note:
_.each(_.range(count), function(i){
...
});
is equivalent to
_.times(count, function(i){
...
});
small is beautiful...
Considering the source of underscore.js says the following about range
:
Generate an integer Array containing an arithmetic progression
I doubt there is a way to do lazy iteration without modifying the source.
If you don't mind getting your hands dirty, dig into the sources of the older but stable and feature-complete MochiKit's Iter module. It tries to create something along the lines of Python's itertools.
精彩评论