Created
October 29, 2013 22:50
-
-
Save adufilie/7224094 to your computer and use it in GitHub Desktop.
JavaScript Dictionary
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Dictionary = (function(){ | |
// http://github.com/adufilie | |
function Dictionary() { | |
this.set = set; | |
this.get = get; | |
Object.defineProperty( | |
this, | |
"primitives", | |
{ | |
configurable: false, | |
writable: false, | |
enumerable: false, | |
value: {} | |
} | |
); | |
}; | |
var hiddenKey = "\x00Dictionary\x00"; | |
var nextId = 1; | |
function getHiddenKey(key) | |
{ | |
if (!key || typeof key != 'object') | |
return 0; | |
var hKey = key[hiddenKey]; | |
if (!hKey) | |
{ | |
Object.defineProperty( | |
key, | |
hiddenKey, | |
{ | |
configurable: false, | |
writable: false, | |
enumerable: false, | |
value: nextId++ | |
} | |
); | |
hKey = key[hiddenKey]; | |
} | |
return hKey; | |
} | |
function set(key, value) | |
{ | |
var hKey = getHiddenKey(key); | |
if (hKey == 0) | |
this.primitives[key] = value; | |
else | |
this[hKey] = value; | |
} | |
function get(key) | |
{ | |
var hKey = getHiddenKey(key); | |
if (hKey == 0) | |
return this.primitives[key]; | |
else | |
return this[hKey]; | |
} | |
return Dictionary; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment