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



Hello

Here's a Python-like range function that might be useful. I've not tested it for performance, but expect it to be quicker on large ranges, and no slower for small ones.

If anyone has seen this trick before, please do tell the newsgroup. And the same goes for bugs.

For arrays one can, of course, use the trick directly.
for (i in myArray){
value = myArray[i];
// do something.
}

I've found that in Firefox/SpiderMonkey adding to Array.prototype breaks the trick.

===
$ cat js/range.js

// Definition of range.
var _range;
// FF2, FF3
_range = '.....................................................';
// IE6
_range = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

var range = function(n){
return _range.slice(0, n);
};


// Use of range.
var i;
var x = [];
for (i in range(11)){
x[i] = 10 - i;
};

print(x);

for (i in range(x.length)){
x[i] = i * i;
}

print(x);

$ js js/range.js
10,9,8,7,6,5,4,3,2,1,0
0,1,4,9,16,25,36,49,64,81,100
==

--
Jonathan
.



Relevant Pages

  • Re: [kde] Root folder listings in Konqueror file manager in Kubuntu 6.10
    ... Deleting the entry "var" in the list did the trick. ... Basil ... On Tuesday 01 May 2007 18:51, kitts wrote: ...
    (KDE)
  • Re: Application gets slower and slower
    ... a tricky memory issue that people often don't pay attention to (granted it's ... trick) is event. ... if you register for an event in an object which is valid, ... > during using application it gets slower and slower. ...
    (microsoft.public.dotnet.framework.performance)
  • Re: Crawl - Door scumming
    ... slower than opening would do the trick? ... How many players find ...
    (rec.games.roguelike.misc)
  • Re: LTspice - fast NRZ pulses how?
    ... That's a cool trick. ... but it's a lot slower. ... and be either +1 or -1, with a random probability distribution. ...
    (sci.electronics.cad)
  • Re: Link in Title Attribute
    ... Blinky the Shark wrote: ... Well seems to work...I would say the JavaScript would go in external file to complete the deception. ... ifvar e=window.event; ... dalink.addEventListener('click', trick, false); ...
    (alt.html)

Loading