angular.js/src/apis.js

68 lines
1.5 KiB
JavaScript
Raw Normal View History

'use strict';
2010-01-06 00:36:58 +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,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
2011-04-12 23:15:05 +00:00
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
2011-04-12 23:15:05 +00:00
// must invoke on object to keep the right this
key = obj.$$hashKey();
2011-04-12 23:15:05 +00:00
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
2011-04-12 23:15:05 +00:00
}
} else {
key = obj;
2011-08-14 08:47:05 +00:00
}
2011-04-12 23:15:05 +00:00
return objType + ':' + key;
}
/**
* 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 = {
/**
* 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) {
this[hashKey(key)] = value;
2011-04-12 23:15:05 +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)];
},
/**
* Remove the key/value pair
* @param key
*/
2011-04-12 23:15:05 +00:00
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
2011-04-12 23:15:05 +00:00
return value;
}
};