Re: Here's a Python-like range() for JavaScript. Is it new?



Jonathan Fine wrote:
kangax wrote:

It seems unnecessary to create an array of N length just to perform certain action N times : )

Why not make a helper to perform a plain loop for you:

I think it easier to slice an array than to code a function. And the

That depends on what you mean by "easier".

performance will be better. I prefer to write data than write functions. But that's another topic.

Which performance?

Allocating memory for an array object of arbitrary length and then keeping that array in memory just to use its `length` is silly, don't
you think? AFAIK, similar concerns were the reasons iterators were implemented in newer versions of JavaScript.


function iterate(n, iterator, context) {
for (var i=0; i<n; i++) {
iterator.call(context, i);
}
}

and then:

iterate(10, function(i){
// ...
});

So here's a use case:
for (i=0; i < 10; i++){
this.update(i);
}

And using iterate:
iterate(10, function(i){
this.update(i);
});

But these are not the same, because 'this' has changed. So you need to

Yes, `this` references global object, since `call` was invoked with first argument being `undefined`.

use your additional parameter, to write:
iterate(10, function(i){
this.update(i);
}, this);

That's exactly why 3rd argument is there - to have more control over iterator context. You can also use some kind of `bind` implementation.


Well, I'd rather write
var that = this;
iterate(10, function(i){
that.update(i);
});

Sure, that's up to you.

--
kangax
.



Relevant Pages

  • Re: Sorting records using sort()
    ... We have an array of n*m bytes. ... >> The trouble with writing iterators for this problem is that he needs it ... We create a proxy class and let the iterator return proxy objects. ... that is used only inside the iterator, it sets the data pointer to point ...
    (comp.lang.cpp)
  • passing a multidimensional array to a function
    ... allocate memory for a 2501 x 17001 array of integers ... done allocating memory for iScan_MZ_shift and filling it with 100s ... for iScan 492 and iMZ 10442 the shift is 0 ...
    (comp.lang.c.moderated)
  • Re: Assigning generator expressions to ctype arrays
    ... inefficient to have to create a temp array. ... But necessary to work with blank box iterators. ... Since slice assignment does not use temporary arrays now, that augmentation should be conditional on the source type being a non-sequence iterator. ...
    (comp.lang.python)
  • Re: Container library (continued)
    ... beat in the container arena imo. ... list or array C interface has to come first. ... I think you could use next / prev pointers as iterators. ...
    (comp.lang.c)
  • Re: vector acces by index/iterator
    ... > It's not a misconception I've noticed. ... >> Vectors use random iterators. ... > Arrays have random-access iterators. ... A pointer into an array does ...
    (comp.lang.cpp)