forked from LeaVerou/StronglyTyped
-
Notifications
You must be signed in to change notification settings - Fork 0
/
strongly-typed.js
243 lines (201 loc) · 5.66 KB
/
strongly-typed.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/**
* Library for strongly typed properties and global variables in JavaScript
* @author Lea Verou
* @version 1.1
* MIT license http://www.opensource.org/licenses/mit-license.php
*/
// Array.prototype.forEach polyfill from MDC
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(fun /*, thisp */) {
"use strict";
if (this === void 0 || this === null) {
throw new TypeError();
}
var t = Object(this), len = t.length >>> 0;
if (typeof fun !== "function") {
throw new TypeError();
}
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
fun.call(thisp, t[i], i, t);
}
}
};
}
// Function.prototype.bind polyfill from MDC
if (!Function.prototype.bind) {
Function.prototype.bind = function(obj) {
var slice = [].slice,
args = slice.call(arguments, 1),
self = this,
nop = function () {},
bound = function () {
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
/*
* The next 20 lines register StronglyTyped as either, an AMD or CommonJS module, and as a browser global.
* Based on UMD's commonjsStrictGlobal.js https://github.com/umdjs/umd/blob/master/commonjsStrictGlobal.js
* Learn more about modular JS, AMD and CommonJS: http://addyosmani.com/writing-modular-js/
* @reference: CommonJS http://requirejs.org/docs/whyamd.html#commonjs
* @reference: AMD http://requirejs.org/docs/whyamd.html#amd
*/
(function (root, factory) {
if (typeof exports === 'object') {
// CommonJS
factory(root, exports);
}
else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['exports'], function (exports) {
//return (root.StronglyTyped = factory(exports, b));
return ( root.StronglyTyped = factory(exports) );
//root.Backbone = factory(root, exports, _, $);
});
}
else {
// Browser globals
root.StronglyTyped = factory(root, {});
}
}(this, function (root, StronglyTyped) {
var objects = [];
var supportsDefineProperty = 'defineProperty' in Object &&
(function(){
var testDOM = document.createElement('div'),
testO = {};
try {
Object.defineProperty(testDOM, 'test', {
get: function(){},
set:function(){}
});
Object.defineProperty(testO, 'test', {
get: function(){},
set:function(){}
});
}
catch(e){
return false;
}
return true;
})();
// Smoothen out differences between Object.defineProperty
// and __defineGetter__/__defineSetter__
if (supportsDefineProperty) {
var defineProperty = Object.defineProperty;
}
else if ('__defineSetter__' in Object) {
var defineProperty = function(o, property, etters) {
o.__defineGetter__(property, etters.get);
o.__defineSetter__(property, etters.set);
};
}
else {
if(window.console && console.warn) {
console.warn('Getters and Setters are not supported so StronglyTyped will fallback to regular properties');
}
// Fallback to regular properties if getters/setters are not supported
var defineProperty = function(o, property, etters) {
o[property] = undefined;
};
}
var self;
self = StronglyTyped = {
/**
* Generic function for defining strongly typed properties.
* You're advised to use the shortcuts defined below.
*/
property: function(type, o, property, value) {
getProperties(o)[property] = value;
defineProperty(o, property, {
get: getter.bind(o, property),
set: setter.bind(o, type, property)
});
o[property] = value;
},
/**
* Constants that can't be changed
*/
constant: function(o, name, value) {
defineProperty(o, name, {
get: getter.bind(o, name),
set: function(value) {
var currentValue = getProperties(this)[name];
if (currentValue === undefined) {
getProperties(this)[name] = value;
}
else {
// ISSUE Should we throw an error?
}
}
});
o[name] = value;
},
/**
* Tests whether a value is of a given type
*/
is: function(type, value) {
switch(type) {
case 'Integer':
return self.is('Number', value) && (isNaN(value) || !isFinite(value) || value % 1 === 0);
default:
return value instanceof window[type] ||
Object.prototype.toString.call(value) === '[object ' + type + ']';
}
}
};
// Shortcuts
[
'Array',
'Boolean',
'Date',
'Function',
'Integer',
'Number',
'RegExp',
'String'
].forEach(function(type) {
self[type.toLowerCase()] = self.property.bind(self, type);
});
/*************************
* Private functions
*************************/
/**
* Generic getter
*/
function getter(property) {
return getProperties(this)[property];
}
/**
* Generic setter
*/
function setter(type, property, value) {
if (self.is(type, value) || value === null || value === undefined) {
getProperties(this)[property] = value;
}
else {
throw TypeError(property + ' must be of type ' + type + '. ' + value + ' is not.');
}
}
/**
* Finds the object and returns its strongly typed properties
*/
function getProperties(o) {
for (var i=0, len=objects.length; i<len; i++) {
if (objects[i].object === o) {
return objects[i].properties;
}
}
// If we're here, it wasn't found so let's add it now
i = objects.push({
object: o,
properties: {}
}) - 1;
return objects[i].properties;
}
return StronglyTyped;
}));