1 /** 2 * @class ハッシュテーブルを表現するクラス 3 * @example 4 * var _index = new Hash(); 5 * _index.set("a", "apple"); 6 * _index.set("b", "blue"); 7 * _index.set("c", "coffee"); 8 * 9 * for (var p = _index.first(); p; p = _index.next()) { 10 * print(p.key+" is for "+p.value); 11 * } 12 */ 13 var Hash = function() { 14 this._map = {}; 15 this._keys = []; 16 this._vals = []; 17 this.reset(); 18 } 19 20 /** 21 * ハッシュテーブルにキーと値のセットを追加します。 22 * @param {String} k キー 23 * @param {*} v 値 24 */ 25 Hash.prototype.set = function(k, v) { 26 if (k != "") { 27 this._keys.push(k); 28 this._map["="+k] = this._vals.length; 29 this._vals.push(v); 30 } 31 } 32 33 /** 34 * 登録されているデータのキーと値を変更します。 35 * @param {String} k 現在のキー 36 * @param {String} k2 新しいキー 37 * @param {*} [v] 新しい値。省略した場合現在の値を変更しません。 38 */ 39 Hash.prototype.replace = function(k, k2, v) { 40 if (k == k2) return; 41 42 var offset = this._map["="+k]; 43 this._keys[offset] = k2; 44 if (typeof v != "undefined") this._vals[offset] = v; 45 this._map["="+k2] = offset; 46 delete(this._map["="+k]); 47 } 48 49 /** 50 * 登録されているデータを削除します。 51 * @param {String} k 削除するデータのキー 52 */ 53 Hash.prototype.drop = function(k) { 54 if (k != "") { 55 var offset = this._map["="+k]; 56 this._keys.splice(offset, 1); 57 this._vals.splice(offset, 1); 58 delete(this._map["="+k]); 59 for (var p in this._map) { 60 if (this._map[p] >= offset) this._map[p]--; 61 } 62 if (this._cursor >= offset && this._cursor > 0) this._cursor--; 63 } 64 } 65 66 /** 67 * キーを指定し、値を返します。 68 * @param {String} k キー 69 * @return {*} 値。キーに対応する値が存在しない場合、undefinedを返します。 70 */ 71 Hash.prototype.get = function(k) { 72 if (k != "") { 73 return this._vals[this._map["="+k]]; 74 } 75 } 76 77 /** 78 * キーの配列を返します。 79 * @return {String[]} キーの配列 80 */ 81 Hash.prototype.keys = function() { 82 return this._keys; 83 } 84 85 /** 86 * キーが存在するかどうかを判定します。 87 * @param {String} k キー 88 * @return {Boolean} キーが存在するならtrue、しないならfalse 89 */ 90 Hash.prototype.hasKey = function(k) { 91 if (k != "") { 92 return (typeof this._map["="+k] != "undefined"); 93 } 94 } 95 96 /** 97 * 値の配列を返します。 98 * @return {*[]} 値の配列 99 */ 100 Hash.prototype.values = function() { 101 return this._vals; 102 } 103 104 /** 105 * データ取得位置を初期化します。 106 */ 107 Hash.prototype.reset = function() { 108 this._cursor = 0; 109 } 110 111 /** 112 * データ取得位置を初期化し、先頭のデータを返します。 113 * @return {Object} キーと値をプロパティに持つオブジェクト 114 * @return {String} .key キー 115 * @return {*} .value 値 116 */ 117 Hash.prototype.first = function() { 118 this.reset(); 119 return this.next(); 120 } 121 122 /** 123 * データ取得位置を1つ進め、次の位置のデータを返します。現在の位置がすでに最後尾の場合、undefinedを返します。 124 * @return {Object} キーと値をプロパティに持つオブジェクト 125 * @return {String} .key キー 126 * @return {*} .value 値 127 */ 128 Hash.prototype.next = function() { 129 if (this._cursor++ < this._keys.length) 130 return {key: this._keys[this._cursor-1], value: this._vals[this._cursor-1]}; 131 }