From bb67ee8d28f2cddb4b503dc8909649994a4d67e1 Mon Sep 17 00:00:00 2001 From: Misko Hevery Date: Tue, 12 Apr 2011 16:15:05 -0700 Subject: Added HashMap --- src/apis.js | 35 +++++++++++++++++++++++++++++++++++ test/ApiSpecs.js | 15 +++++++++++++++ 2 files changed, 50 insertions(+) diff --git a/src/apis.js b/src/apis.js index 237a1c1c..11fa9838 100644 --- a/src/apis.js +++ b/src/apis.js @@ -807,6 +807,39 @@ var angularFunction = { } }; +function hashKey(obj) { + var objType = typeof obj; + var key = obj; + if (objType == 'object') { + if (typeof (key = obj.$hashKey) == 'function') { + // must invoke on object to keep the right this + key = obj.$hashKey(); + } else if (key === undefined) { + key = obj.$hashKey = nextUid(); + } + }; + return objType + ':' + key; +} + +function HashMap(){} +HashMap.prototype = { + put: function(key, value) { + var _key = hashKey(key); + var oldValue = this[_key]; + this[_key] = value; + return oldValue; + }, + get: function(key) { + return this[hashKey(key)]; + }, + remove: function(key) { + var _key = hashKey(key); + var value = this[_key]; + delete this[_key]; + return value; + } +}; + function defineApi(dst, chain){ angular[dst] = angular[dst] || {}; forEach(chain, function(parent){ @@ -819,6 +852,8 @@ defineApi('Array', [angularGlobal, angularCollection, angularArray]); defineApi('Object', [angularGlobal, angularCollection, angularObject]); defineApi('String', [angularGlobal, angularString]); defineApi('Date', [angularGlobal, angularDate]); +// TODO: enable and document this API +//defineApi('HashMap', [HashMap]); //IE bug angular['Date']['toString'] = angularDate['toString']; defineApi('Function', [angularGlobal, angularCollection, angularFunction]); diff --git a/test/ApiSpecs.js b/test/ApiSpecs.js index 0383a457..2fd51873 100644 --- a/test/ApiSpecs.js +++ b/test/ApiSpecs.js @@ -252,5 +252,20 @@ describe('api', function(){ assertEquals({a:1, b:2}, angular.Object.extend({a:1}, {b:2})); }); + describe('HashMap', function(){ + it('should do basic crud', function(){ + var map = new HashMap(); + var key = {}; + var value1 = {}; + var value2 = {}; + expect(map.put(key, value1)).toEqual(undefined); + expect(map.put(key, value2)).toEqual(value1); + expect(map.get(key)).toEqual(value2); + expect(map.get({})).toEqual(undefined); + expect(map.remove(key)).toEqual(value2); + expect(map.get(key)).toEqual(undefined); + }); + }); + }); -- cgit v1.2.3