/* To those who think they saw this before:
I have deleted my previous posts. this is a new post with
code that actually works (!)
The importance of testing code before publishing
*/
//Assume the associative array:
meals = new Array(0);
meals["fish"] = "kipper";
meals["pasta"] = "spagbol";
meals["curry"] = "tandoori";
meals["meat"] = "tartare";
// There are no "indexes", there are "keys".
// get an array of keys:
k = new Array(0);
for(i in meals) {
k[k.length] = i;
}
k.sort(); // to sort the keys alphabetically, not required, can be
useful
// otherwise there is no contract as to whether
// the keys will be returned in insertion order or not
// You can thus get the items in defined order and via numeric index
meals[ k[3] ];
/*
Try otherwise a data type: the following can be passed an associative
array, to get a data type that holds the array and can be iterated over
with function calls, with the option of sorting the keys. Calling item(
number ) gets the corresponding item. calls to next() and prev() do
what you'd expect
On calling prev() or next() at the start or end respectively of the
array will return null and the counter will be reset to the opposite
end of the array, and return null.
(see further for example of use)
*/
function Iterator(src_array,sorting) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;
for(var n in this.internal) {
this.keys[this.keys.length] = n;
}
if(sorting) {this.keys.sort();}
}
function getnextitem() {
++this.i;
if( this.i >= this.keys.length ) {this.i = -1;return null;}
return this.internal[ this.keys[this.i] ];
}
function getprevitem() {
--this.i;
if( this.i < 0 ) {this.i = this.keys.length;return null;}
return this.internal[ this.keys[this.i] ];
}
function getitem(idx) {
if( idx >= this.keys.length || idx < 0 ) {return null;}
this.i = idx;
return this.internal[ this.keys[idx] ];
}
function getsize() {return this.keys.length;}
Iterator.prototype.next = getnextitem;
Iterator.prototype.prev = getprevitem;
Iterator.prototype.item = getitem;
Iterator.prototype.size = getsize;
// === example of use:
mealiterator = new Iterator(meals,true);
document.write(mealiterator.item(2)+", " );// tartare
document.write(mealiterator.next()+", " );// spagbol
document.write(mealiterator.next()+", " );// null
document.write(mealiterator.next()+"<br>" );// tandoori (we are back at
the start)
document.write(mealiterator.item(1)+", " );// kipper
document.write(mealiterator.prev()+", " );// tandoori
document.write(mealiterator.prev()+", " );// null
document.write(mealiterator.prev()+"<br>" );// spagbol - back at end