-
-
Save jaawerth/7ef0e8330cb9def14687 to your computer and use it in GitHub Desktop.
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
// with defined properties | |
function accessors(index) { | |
return { | |
enumerable: true, configurable: false, | |
get: function() { return this._value[index]; }, | |
set: function(value) { this._value[index] = value; } | |
}; | |
} | |
function defineTypeWithDefinedProperties(fields) { | |
function Type(values) { this._value = values || []; } | |
var _len = fields.length, properties = {}; | |
for (var i = 0; i < _len; ++i) properties[fields[i].name] = accessors(i); | |
Type.prototype = Object.create(Object.prototype, properties); | |
return Type; | |
} | |
// with get/set on prototype | |
function defineTypeWithGetSetOnPrototype(fields) { | |
function Type(values) { this._value = values || []; } | |
var _len = fields.length, properties = {}; | |
for (var i = 0; i < _len; ++i) properties[fields[i].name] = i; | |
Type.prototype.properties = properties; | |
Type.prototype.get = function(prop) { | |
return this._value[Type.prototype.properties[prop]]; | |
}; | |
Type.prototype.set = function(prop, value) { | |
this._value[Type.prototype.properties[prop]] = value; | |
}; | |
return Type; | |
} | |
// prep | |
var fields = [ { name: 'first' }, { name: 'second' } ]; | |
var WithDefinedProperties = defineTypeWithDefinedProperties(fields); | |
var WithGetSetOnPrototype = defineTypeWithGetSetOnPrototype(fields); | |
var definedWithValues = new WithDefinedProperties([1, "two"]); | |
var definedWithNoValues = new WithDefinedProperties(); | |
var getSetWithValues = new WithGetSetOnPrototype([1, "two"]); | |
var getSetWithNoValues = new WithGetSetOnPrototype(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment