Upgrade to ExtJS 4.0.0 - Released 04/26/2011
[extjs.git] / src / util / HashMap.js
1 /**
2  * @class Ext.util.HashMap
3  * <p>
4  * Represents a collection of a set of key and value pairs. Each key in the HashMap
5  * must be unique, the same key cannot exist twice. Access to items is provided via
6  * the key only. Sample usage:
7  * <pre><code>
8 var map = new Ext.util.HashMap();
9 map.add('key1', 1);
10 map.add('key2', 2);
11 map.add('key3', 3);
12
13 map.each(function(key, value, length){
14     console.log(key, value, length);
15 });
16  * </code></pre>
17  * </p>
18  *
19  * <p>The HashMap is an unordered class,
20  * there is no guarantee when iterating over the items that they will be in any particular
21  * order. If this is required, then use a {@link Ext.util.MixedCollection}.
22  * </p>
23  * @constructor
24  * @param {Object} config The configuration options
25  */
26 Ext.define('Ext.util.HashMap', {
27
28     /**
29      * @cfg {Function} keyFn A function that is used to retrieve a default key for a passed object.
30      * A default is provided that returns the <b>id</b> property on the object. This function is only used
31      * if the add method is called with a single argument.
32      */
33
34     mixins: {
35         observable: 'Ext.util.Observable'
36     },
37
38     constructor: function(config) {
39         var me = this;
40
41         me.addEvents(
42             /**
43              * @event add
44              * Fires when a new item is added to the hash
45              * @param {Ext.util.HashMap} this.
46              * @param {String} key The key of the added item.
47              * @param {Object} value The value of the added item.
48              */
49             'add',
50             /**
51              * @event clear
52              * Fires when the hash is cleared.
53              * @param {Ext.util.HashMap} this.
54              */
55             'clear',
56             /**
57              * @event remove
58              * Fires when an item is removed from the hash.
59              * @param {Ext.util.HashMap} this.
60              * @param {String} key The key of the removed item.
61              * @param {Object} value The value of the removed item.
62              */
63             'remove',
64             /**
65              * @event replace
66              * Fires when an item is replaced in the hash.
67              * @param {Ext.util.HashMap} this.
68              * @param {String} key The key of the replaced item.
69              * @param {Object} value The new value for the item.
70              * @param {Object} old The old value for the item.
71              */
72             'replace'
73         );
74
75         me.mixins.observable.constructor.call(me, config);
76         me.clear(true);
77     },
78
79     /**
80      * Gets the number of items in the hash.
81      * @return {Number} The number of items in the hash.
82      */
83     getCount: function() {
84         return this.length;
85     },
86
87     /**
88      * Implementation for being able to extract the key from an object if only
89      * a single argument is passed.
90      * @private
91      * @param {String} key The key
92      * @param {Object} value The value
93      * @return {Array} [key, value]
94      */
95     getData: function(key, value) {
96         // if we have no value, it means we need to get the key from the object
97         if (value === undefined) {
98             value = key;
99             key = this.getKey(value);
100         }
101
102         return [key, value];
103     },
104
105     /**
106      * Extracts the key from an object. This is a default implementation, it may be overridden
107      * @private
108      * @param {Object} o The object to get the key from
109      * @return {String} The key to use.
110      */
111     getKey: function(o) {
112         return o.id;
113     },
114
115     /**
116      * Adds an item to the collection. Fires the {@link #add} event when complete.
117      * @param {String} key <p>The key to associate with the item, or the new item.</p>
118      * <p>If a {@link #getKey} implementation was specified for this HashMap,
119      * or if the key of the stored items is in a property called <tt><b>id</b></tt>,
120      * the HashMap will be able to <i>derive</i> the key for the new item.
121      * In this case just pass the new item in this parameter.</p>
122      * @param {Object} o The item to add.
123      * @return {Object} The item added.
124      */
125     add: function(key, value) {
126         var me = this,
127             data;
128
129         if (arguments.length === 1) {
130             value = key;
131             key = me.getKey(value);
132         }
133
134         if (me.containsKey(key)) {
135             me.replace(key, value);
136         }
137
138         data = me.getData(key, value);
139         key = data[0];
140         value = data[1];
141         me.map[key] = value;
142         ++me.length;
143         me.fireEvent('add', me, key, value);
144         return value;
145     },
146
147     /**
148      * Replaces an item in the hash. If the key doesn't exist, the
149      * {@link #add} method will be used.
150      * @param {String} key The key of the item.
151      * @param {Object} value The new value for the item.
152      * @return {Object} The new value of the item.
153      */
154     replace: function(key, value) {
155         var me = this,
156             map = me.map,
157             old;
158
159         if (!me.containsKey(key)) {
160             me.add(key, value);
161         }
162         old = map[key];
163         map[key] = value;
164         me.fireEvent('replace', me, key, value, old);
165         return value;
166     },
167
168     /**
169      * Remove an item from the hash.
170      * @param {Object} o The value of the item to remove.
171      * @return {Boolean} True if the item was successfully removed.
172      */
173     remove: function(o) {
174         var key = this.findKey(o);
175         if (key !== undefined) {
176             return this.removeAtKey(key);
177         }
178         return false;
179     },
180
181     /**
182      * Remove an item from the hash.
183      * @param {String} key The key to remove.
184      * @return {Boolean} True if the item was successfully removed.
185      */
186     removeAtKey: function(key) {
187         var me = this,
188             value;
189
190         if (me.containsKey(key)) {
191             value = me.map[key];
192             delete me.map[key];
193             --me.length;
194             me.fireEvent('remove', me, key, value);
195             return true;
196         }
197         return false;
198     },
199
200     /**
201      * Retrieves an item with a particular key.
202      * @param {String} key The key to lookup.
203      * @return {Object} The value at that key. If it doesn't exist, <tt>undefined</tt> is returned.
204      */
205     get: function(key) {
206         return this.map[key];
207     },
208
209     /**
210      * Removes all items from the hash.
211      * @return {Ext.util.HashMap} this
212      */
213     clear: function(/* private */ initial) {
214         var me = this;
215         me.map = {};
216         me.length = 0;
217         if (initial !== true) {
218             me.fireEvent('clear', me);
219         }
220         return me;
221     },
222
223     /**
224      * Checks whether a key exists in the hash.
225      * @param {String} key The key to check for.
226      * @return {Boolean} True if they key exists in the hash.
227      */
228     containsKey: function(key) {
229         return this.map[key] !== undefined;
230     },
231
232     /**
233      * Checks whether a value exists in the hash.
234      * @param {Object} value The value to check for.
235      * @return {Boolean} True if the value exists in the dictionary.
236      */
237     contains: function(value) {
238         return this.containsKey(this.findKey(value));
239     },
240
241     /**
242      * Return all of the keys in the hash.
243      * @return {Array} An array of keys.
244      */
245     getKeys: function() {
246         return this.getArray(true);
247     },
248
249     /**
250      * Return all of the values in the hash.
251      * @return {Array} An array of values.
252      */
253     getValues: function() {
254         return this.getArray(false);
255     },
256
257     /**
258      * Gets either the keys/values in an array from the hash.
259      * @private
260      * @param {Boolean} isKey True to extract the keys, otherwise, the value
261      * @return {Array} An array of either keys/values from the hash.
262      */
263     getArray: function(isKey) {
264         var arr = [],
265             key,
266             map = this.map;
267         for (key in map) {
268             if (map.hasOwnProperty(key)) {
269                 arr.push(isKey ? key: map[key]);
270             }
271         }
272         return arr;
273     },
274
275     /**
276      * Executes the specified function once for each item in the hash.
277      * Returning false from the function will cease iteration.
278      *
279      * The paramaters passed to the function are:
280      * <div class="mdetail-params"><ul>
281      * <li><b>key</b> : String<p class="sub-desc">The key of the item</p></li>
282      * <li><b>value</b> : Number<p class="sub-desc">The value of the item</p></li>
283      * <li><b>length</b> : Number<p class="sub-desc">The total number of items in the hash</p></li>
284      * </ul></div>
285      * @param {Function} fn The function to execute.
286      * @param {Object} scope The scope to execute in. Defaults to <tt>this</tt>.
287      * @return {Ext.util.HashMap} this
288      */
289     each: function(fn, scope) {
290         // copy items so they may be removed during iteration.
291         var items = Ext.apply({}, this.map),
292             key,
293             length = this.length;
294
295         scope = scope || this;
296         for (key in items) {
297             if (items.hasOwnProperty(key)) {
298                 if (fn.call(scope, key, items[key], length) === false) {
299                     break;
300                 }
301             }
302         }
303         return this;
304     },
305
306     /**
307      * Performs a shallow copy on this hash.
308      * @return {Ext.util.HashMap} The new hash object.
309      */
310     clone: function() {
311         var hash = new this.self(),
312             map = this.map,
313             key;
314
315         hash.suspendEvents();
316         for (key in map) {
317             if (map.hasOwnProperty(key)) {
318                 hash.add(key, map[key]);
319             }
320         }
321         hash.resumeEvents();
322         return hash;
323     },
324
325     /**
326      * @private
327      * Find the key for a value.
328      * @param {Object} value The value to find.
329      * @return {Object} The value of the item. Returns <tt>undefined</tt> if not found.
330      */
331     findKey: function(value) {
332         var key,
333             map = this.map;
334
335         for (key in map) {
336             if (map.hasOwnProperty(key) && map[key] === value) {
337                 return key;
338             }
339         }
340         return undefined;
341     }
342 });