1/***************************************************************************** 2 * 3 * Copyright (c) 2004-2007 Guido Wesdorp. All rights reserved. 4 * 5 * This software is distributed under the terms of the JSBase 6 * License. See LICENSE.txt for license text. 7 * 8 *****************************************************************************/ 9 10var global = this; 11global.array = new function() { 12 var array = this; 13 14 this.contains = function(a, element, objectequality) { 15 /* see if some value is in a */ 16 // DEPRECATED!!! use array.indexOf instead 17 return (this.indexOf(a, element, !objectequality) > -1); 18 }; 19 20 this.indexOf = function(a, element, compareValues) { 21 for (var i=0; i < a.length; i++) { 22 if (!compareValues) { 23 if (element === a[i]) { 24 return i; 25 }; 26 } else { 27 if (element == a[i]) { 28 return i; 29 }; 30 }; 31 }; 32 return -1; 33 }; 34 35 this.removeDoubles = function(a) { 36 var ret = []; 37 for (var i=0; i < a.length; i++) { 38 if (!this.contains(ret, a[i])) { 39 ret.push(a[i]); 40 }; 41 }; 42 return ret; 43 }; 44 45 this.map = function(a, func) { 46 /* apply 'func' to each element in the array (in-place!!) */ 47 for (var i=0; i < a.length; i++) { 48 a[i] = func(a[i]); 49 }; 50 return this; 51 }; 52 53 this.reversed = function(a) { 54 var ret = []; 55 for (var i = a.length; i > 0; i--) { 56 ret.push(a[i - 1]); 57 }; 58 return ret; 59 }; 60 61 this.StopIteration = function(message) { 62 if (message !== undefined) { 63 this._initialize('StopIteration', message); 64 }; 65 }; 66 67 if (global.exception) { 68 StopIteration.prototype = global.exception.Exception; 69 }; 70 71 var Iterator = this.Iterator = function(a) { 72 if (a) { 73 this._initialize(a); 74 }; 75 }; 76 77 Iterator._initialize = function(a) { 78 this._array = a; 79 this._i = 0; 80 }; 81 82 Iterator.next = function() { 83 if (this._i >= this._array.length) { 84 this._i = 0; 85 throw(StopIteration('no more items')); 86 }; 87 return this._i++; 88 }; 89 90 this.iterate = function(a) { 91 /* iterate through array 'a' 92 93 this returns the n-th item of array 'a', where n is the number of 94 times this function has been called on 'a' before 95 96 when the items are all visited, the function resets the counter and 97 starts from the start 98 99 note that this annotates the array with information about iteration 100 using the attribute '__iter_index__', remove this or set to 0 to 101 reset 102 103 this does not work well with arrays that have 'undefined' as one of 104 their values!! 105 */ 106 if (!a.__iter_index__) { 107 a.__iter_index__ = 0; 108 } else if (a.__iter_index__ >= a.length) { 109 a.__iter_index__ = undefined; 110 return undefined; 111 }; 112 return a[a.__iter_index__++]; 113 }; 114}(); 115