Created
July 1, 2014 17:02
-
-
Save jkrems/b7056c00701b362ef7b6 to your computer and use it in GitHub Desktop.
Safe object/dictionary in JavaScript
This file contains hidden or 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
/* jshint node:true, esnext:true */ | |
'use strict'; | |
// Run: node --harmony_proxies --harmony-collections safe-map.js | |
function createSafeObject(props) { | |
if (typeof props !== 'object' || props === null) { | |
props = {}; | |
} | |
var m = new Map(); | |
var keys = []; | |
for (var k in props) { | |
if (props.hasOwnProperty(k)) { | |
m.set(k, props[k]); | |
} | |
} | |
return Proxy.create({ | |
has: function(name) { | |
return m.has(name); | |
}, | |
hasOwn: function(name) { | |
return m.has(name); | |
}, | |
get: function(receiver, name) { | |
if (!m.has(name)) { | |
throw new Error('Unknown property: ' + name); | |
} | |
return m.get(name); | |
}, | |
set: function(receiver, name, val) { | |
if (keys.indexOf(name) === -1) { | |
keys.push(name); | |
} | |
return m.set(name, val); | |
}, | |
delete: function(name) { | |
if (keys.indexOf(name) === -1) { | |
keys = keys.filter(function(key) { | |
return key !== name; | |
}); | |
} | |
return m.delete(name); | |
}, | |
enumerate: function() { | |
return keys; | |
}, | |
keys: function() { | |
return keys; | |
} | |
}, m); | |
} | |
var obj = createSafeObject({ x: 10, y: 20 }); | |
console.log('Position: %s/%s', obj.x, obj.y); | |
try { | |
console.log(obj.z); | |
} catch (err) { | |
console.log('Expected error:\n %s', err.message); | |
} | |
obj.z = 40; | |
console.log('Position: %s/%s/%s', obj.x, obj.y, obj.z); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment