Skip to content

Instantly share code, notes, and snippets.

@adufilie
Created October 29, 2013 22:50
Show Gist options
  • Save adufilie/7224094 to your computer and use it in GitHub Desktop.
Save adufilie/7224094 to your computer and use it in GitHub Desktop.
JavaScript Dictionary
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