开发者

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜