Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy range iteration in javascript using underscore

I've caught myself using this in place 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?

like image 375
v_y Avatar asked Sep 26 '11 05:09

v_y


People also ask

What is _ each in JavaScript?

Collection Functions (Arrays or Objects) each _.each(list, iteratee, [context]) Alias: forEach. Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed.

How do you use underscore in JavaScript?

Adding Underscore to a Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.

What is underscore variable in JavaScript?

It is simply the convention of prepending an underscore ( _ ) to a variable name. This is done to indicate that a variable is private and should not be toyed with. For example, a "private" variable that stores sensitive information, such as a password, will be named _password to explicitly state that it is "private".


1 Answers

Just a note:

_.each(_.range(count), function(i){
  ...
});

is equivalent to

_.times(count, function(i){
  ...
});

small is beautiful...

like image 56
nderoche Avatar answered Oct 01 '22 04:10

nderoche