Created
May 1, 2013 19:27
-
-
Save mhseiden/5497675 to your computer and use it in GitHub Desktop.
Version 1 a "typed object" implementation.
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
/** | |
Copyright (c) 2012 - Max Seiden <[email protected]> | |
Permission is hereby granted, free of charge, to any person obtaining a copy of | |
this software and associated documentation files (the "Software"), to deal in | |
the Software without restriction, including without limitation the rights to | |
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of | |
the Software, and to permit persons to whom the Software is furnished to do so, | |
subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS | |
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR | |
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER | |
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN | |
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
**/ | |
// Requires, Consts, Errors, and Config | |
//////////////////////////////////////////////////////////////////////////////// | |
// Requires | |
var Common = require('./common') | |
, Util = require('util') | |
; | |
// Error string for invalid type assignment | |
const SET_ERROR_c = 'Cannot assign \'{t1} {name}\' to type \'{t2}\'.'; | |
const PROP_REASSIGN_ERROR_c = 'Property \'{name}\' is already assigned.'; | |
// Specify and add the default data type generators | |
const GENERATORS_c = [ | |
function() {return 0;} | |
, function() {return [];} | |
, function() {return {};} | |
, function() {return '';} | |
, function() {return false;} | |
, function() {return new Date()} | |
, function() {return new RegExp()} | |
]; | |
// Error for invalid assignment | |
var AssignmentError = | |
module.exports.AssignmentError = | |
function AssignmentError(error_string) | |
{ | |
this.name = "AssignmentError"; | |
this.message = error_string.concat(new Error().stack.replace(/^Error/, "")); | |
} | |
// Error when trying to reassign a property | |
var ReassignError = | |
module.exports.ReassignError = | |
function ReassignError(error_string) | |
{ | |
this.name = "ReassignError"; | |
this.message = error_string.concat(new Error().stack.replace(/^Error/, "")); | |
} | |
var TypedObject = | |
module.exports.instanceConstructor = | |
function() {}; | |
// Typed Assignment | |
//////////////////////////////////////////////////////////////////////////////// | |
var createTyped = | |
module.exports.create = | |
function createTyped() | |
{ | |
return makeTyped.call(this, new TypedObject()); | |
} | |
var makeTyped = | |
function makeTyped(obj) | |
{ | |
// *.createTyped() should be used instead, but just in case... | |
obj = obj || {}; | |
if(obj._isTypedObj) {throw Error('Object is already a \'TypedObject\'')} | |
Common.addImmutableProperty(obj, '_isTypedObj', true); | |
// Add Private properties | |
Common.addPrivateProperty(obj, '_data', {}); | |
// Register type assigners | |
GENERATORS_c.forEach(function(typeGenerator) { | |
registerTypeAssigner(obj, typeGenerator); | |
}); | |
return obj; | |
} | |
var registerTypeAssigner = | |
function registerTypeAssigner(obj, typeGenerator) | |
{ | |
var typeDefault = typeGenerator() | |
, typeName = Common.typeOf(typeDefault) | |
; | |
Object.defineProperty(obj, typeName, { | |
writeable: false | |
, configurable: false | |
, enumerable: false | |
, value: function(propName) { | |
// Disallow overwriting of properties | |
var error_string = PROP_REASSIGN_ERROR_c | |
.replace('{name}', propName) | |
; | |
// Property reassignment error | |
if(this[propName]) {throw new ReassignError(error_string);} | |
// Assign properties | |
this._data[propName] = typeDefault; | |
// Add typed gette and setter | |
addGetterSetter(this, propName, typeName); | |
// Return the obj to make these chainable. (Could be useful...?) | |
return this; | |
} | |
}); | |
} | |
var addGetterSetter = function addGetterSetter(obj, propName, typeName) | |
{ | |
Object.defineProperty(obj, propName, { | |
enumerable: true | |
, configurable: false | |
, get: function() {return this._data[propName];} | |
, set: function(val) { | |
if(!validators[typeName](val)) { | |
throw buildTypeError(val, typeName, propName); | |
} else { | |
this._data[propName] = val; | |
} | |
} | |
}); | |
} | |
var buildTypeError = function buildTypeError(val, typeName, propName) | |
{ | |
var error_string = SET_ERROR_c | |
.replace('{t1}', typeName) | |
.replace('{name}', propName) | |
.replace('{t2}', Common.typeOf(val)) | |
; | |
return new AssignmentError(error_string); | |
} | |
// Type Validation | |
//////////////////////////////////////////////////////////////////////////////// | |
// initialize the validator hash | |
var validators = {}; | |
// Uniform way of adding types | |
var addValidator = function addType(typeGenerator) | |
{ | |
if(!(typeof(typeGenerator) === 'function')) { | |
throw TypeError('Type Generator is not a \'function\''); | |
} | |
// Build validator and assigner | |
buildTypeValidator(Common.typeOf(typeGenerator())); | |
} | |
// Dynamically generate validators | |
var buildTypeValidator = function buildTypeValidator(typeName) | |
{ | |
// Make sure there isn't going to be a collision | |
if(validators[typeName]) {throw Error('Validator exists for type!')} | |
// Build the validator | |
validators[typeName] = (function(typeName) { | |
return function(val) {return Common.typeOf(val) === typeName}; | |
})(typeName); | |
} | |
// Add the default validators | |
GENERATORS_c.forEach(addValidator); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment