2011-07-17 08:05:43 +00:00
|
|
|
'use strict';
|
|
|
|
|
|
2010-01-06 00:36:58 +00:00
|
|
|
|
2011-04-18 23:33:30 +00:00
|
|
|
/**
|
|
|
|
|
* Computes a hash of an 'obj'.
|
|
|
|
|
* Hash of a:
|
|
|
|
|
* string is string
|
|
|
|
|
* number is number as string
|
2011-09-08 20:56:29 +00:00
|
|
|
* object is either result of calling $$hashKey function on the object or uniquely generated id,
|
2011-08-17 06:08:13 +00:00
|
|
|
* that is also assigned to the $$hashKey property of the object.
|
2011-06-20 20:50:46 +00:00
|
|
|
*
|
2011-04-18 23:33:30 +00:00
|
|
|
* @param obj
|
2011-11-10 05:18:34 +00:00
|
|
|
* @returns {string} hash string such that the same input will have the same hash string.
|
2011-08-17 06:08:13 +00:00
|
|
|
* The resulting string key is in 'type:hashKey' format.
|
2011-04-18 23:33:30 +00:00
|
|
|
*/
|
2011-04-12 23:15:05 +00:00
|
|
|
function hashKey(obj) {
|
2012-01-06 07:03:45 +00:00
|
|
|
var objType = typeof obj,
|
|
|
|
|
key;
|
|
|
|
|
|
|
|
|
|
if (objType == 'object' && obj !== null) {
|
2011-08-17 06:08:13 +00:00
|
|
|
if (typeof (key = obj.$$hashKey) == 'function') {
|
2011-04-12 23:15:05 +00:00
|
|
|
// must invoke on object to keep the right this
|
2011-08-17 06:08:13 +00:00
|
|
|
key = obj.$$hashKey();
|
2011-04-12 23:15:05 +00:00
|
|
|
} else if (key === undefined) {
|
2011-08-17 06:08:13 +00:00
|
|
|
key = obj.$$hashKey = nextUid();
|
2011-04-12 23:15:05 +00:00
|
|
|
}
|
2012-01-06 07:03:45 +00:00
|
|
|
} else {
|
|
|
|
|
key = obj;
|
2011-08-14 08:47:05 +00:00
|
|
|
}
|
2012-01-06 07:03:45 +00:00
|
|
|
|
2011-04-12 23:15:05 +00:00
|
|
|
return objType + ':' + key;
|
|
|
|
|
}
|
|
|
|
|
|
2011-04-18 23:33:30 +00:00
|
|
|
/**
|
|
|
|
|
* HashMap which can use objects as keys
|
|
|
|
|
*/
|
2011-09-08 20:56:29 +00:00
|
|
|
function HashMap(array){
|
|
|
|
|
forEach(array, this.put, this);
|
|
|
|
|
}
|
2011-04-12 23:15:05 +00:00
|
|
|
HashMap.prototype = {
|
2011-04-18 23:33:30 +00:00
|
|
|
/**
|
|
|
|
|
* Store key value pair
|
|
|
|
|
* @param key key to store can be any type
|
|
|
|
|
* @param value value to store can be any type
|
|
|
|
|
*/
|
2011-04-12 23:15:05 +00:00
|
|
|
put: function(key, value) {
|
2011-08-17 06:08:13 +00:00
|
|
|
this[hashKey(key)] = value;
|
2011-04-12 23:15:05 +00:00
|
|
|
},
|
2011-06-20 20:50:46 +00:00
|
|
|
|
2011-04-18 23:33:30 +00:00
|
|
|
/**
|
|
|
|
|
* @param key
|
|
|
|
|
* @returns the value for the key
|
|
|
|
|
*/
|
2011-04-12 23:15:05 +00:00
|
|
|
get: function(key) {
|
|
|
|
|
return this[hashKey(key)];
|
|
|
|
|
},
|
2011-06-20 20:50:46 +00:00
|
|
|
|
2011-04-18 23:33:30 +00:00
|
|
|
/**
|
|
|
|
|
* Remove the key/value pair
|
|
|
|
|
* @param key
|
|
|
|
|
*/
|
2011-04-12 23:15:05 +00:00
|
|
|
remove: function(key) {
|
2011-08-17 06:08:13 +00:00
|
|
|
var value = this[key = hashKey(key)];
|
|
|
|
|
delete this[key];
|
2011-04-12 23:15:05 +00:00
|
|
|
return value;
|
|
|
|
|
}
|
|
|
|
|
};
|