Created
September 13, 2011 20:17
-
-
Save rwaldron/1215024 to your computer and use it in GitHub Desktop.
TypedObject Constructor
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
(function( global ) { | |
global.TypedObject = function( obj ) { | |
var keys = Object.keys( obj || {} ), | |
len = keys.length, | |
data = {}, | |
typeOf = { | |
// prop: type | |
}, | |
k = -1; | |
if ( len ) { | |
while ( ++k < len ) { | |
var key = keys[ k ], | |
val = obj[ key ]; | |
data[ key ] = val; | |
typeOf[ key ] = typeof val; | |
} | |
} | |
return Proxy.create({ | |
get: function( r, name ) { | |
return data; | |
}, | |
set: function( r, name, value ) { | |
var type = typeOf[ name ]; | |
if ( !type ) { | |
type = typeOf[ name ] = typeof value; | |
} | |
if ( typeof value !== type ) { | |
throw new Error( | |
"Property value type mismatch for `" + name + "`: expected " + type + ", saw " + typeof value | |
); | |
} | |
data[ name ] = value; | |
} | |
}, Object.prototype ); | |
}; | |
})( this ); | |
var o = new TypedObject(); | |
o.foo = "string"; | |
try { | |
o.foo = 1; | |
} catch(e) { | |
console.log( e ); | |
// > "Property value type mismatch for `foo`: expected string, saw number | |
} | |
console.log( o ); | |
o = new TypedObject({ foo: 1 }); | |
console.log( o ); | |
try { | |
o.foo = []; | |
} catch(e) { | |
console.log( e ); | |
// > "Property value type mismatch for `foo`: expected number, saw object | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://jsbin.com/esacik/10