-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuno.js
executable file
·433 lines (380 loc) · 16.2 KB
/
uno.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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
////////////////////////////////////////////////////////////////////////////////
//
// uno - The simplest unit testing framework possible.
//
// (c) 2012 Evan Moran
// uno.js is freely distributable under the MIT license.
// http://github.com/evanmoran/uno
//
// Function testing (automatic naming)
//
// uno(fn, args, expected)
//
// function sum(a,b){return a+b;}
// uno(sum, [1,2], 3);
// -> "Uno test passed: sum(1,2) == 3"
//
// Function testing (custom name):
//
// uno(name, fn, args, expected)
//
// uno("square({args}) == {expected}", function(a){a*a}, [3], 9)
// -> "Uno test passed: square(3) == 9"
//
// Method testing (custom name):
//
// uno(name, object, method, args, expected)
//
// uno("Math.{method}({args}) == {expected}", Math, Math.round, [1.5], 2);
// -> "Uno test passed: Math.round(1.5) == 2"
//
// Value testing: (not yet implemented)
//
// uno(name, value, expected)
//
// uno("Math.pi == {expected}", Math.pi, 3.14);
// -> "Uno test passed: Math.PI == 3.14"
//
// Profiling (not yet implemented)
//
// uno(fn, args, expected, count)
//
// uno(Math.round, [1.5], 2, 1000)
// -> "Uno test passed: round(1.5) == 2 [Averages 20 ms over 1000 trials]"
//
////////////////////////////////////////////////////////////////////////////////
(function () {
////////////////////////////////////////////////////////////////////////////
// uno function
////////////////////////////////////////////////////////////////////////////
// Current version.
var VERSION = '0.0.2';
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previous = root.uno;
////////////////////////////////////////////////////////////////////////////
// uno helpers
////////////////////////////////////////////////////////////////////////////
//
// Portions of these helper methods were inspired or borrowed from underscore:
// http://github.com/documentcloud/underscore
var _isUndefined = function(obj) { return obj === void 0; };
var _isNull = function(obj) { return obj === null; };
var _isNaN = function (obj) { return obj !== obj; };
var _isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) == '[object Boolean]' };
var _isNumber = function(obj) { return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed)); };
var _isFinite = function(obj) { return _isNumber(obj) && isFinite(obj); };
var _isInfinity = function(obj){ return _isNumber(obj) && !isFinite(obj) && !_isNaN(obj); };
var _isString = function(obj) { return !!(obj === '' || (obj && obj.charCodeAt && obj.substr)); };
var _isDate = function (obj) { return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear); };
var _isRegExp = function (obj) { return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false)); };
var _isElement = function(obj){ return !!(obj && obj.nodeType == 1); };
var _isFunction = function(obj) { return typeof obj === 'function'; };
var _isArray = Array.isArray || function(obj) { return toString.call(obj) == '[object Array]'; };
var _isArguments = function(obj){ return !!(obj && Object.prototype.hasOwnProperty.call(obj, 'callee')); };
var _has = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); };
// _each: Iterate over an object
var _each = function(obj, iterator, context) {
if (obj == null) return;
if (Array.prototype.forEach && obj.forEach === Array.prototype.forEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// _keys: Get the keys of an object
var _keys = Object.keys || function (obj){
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// _extend: Extend a given object with an objects properties
var _extend = function(obj) {
_each(Array.prototype.slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// _defaults: Fill in a given object with default properties.
var _defaults = function(obj) {
_each(Array.prototype.slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// _isSame: Determine if two values are equal
//
// Importantly NaN == NaN should return true for unit testing.
var _isSame = function (a, b)
{
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof (a), btype = typeof (b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// One of them implements an isEqual()?
if (_isFunction(a.isEqual)) return a.isEqual(b);
// Check dates' integer values.
if (_isDate(a) && _isDate(b)) return a.getTime() === b.getTime();
// Both are NaN?
if (_isNaN(a) && _isNaN(b)) return true;
// Compare regular expressions.
if (_isRegExp(a) && _isRegExp(b))
return a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
var aKeys = _keys(a), bKeys = _keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !_isSame(a[key], b[key])) return false;
return true;
};
// _typeOf: Mimic behavior of built-in typeof operator using improved underscore type detection
var _typeOf = function(any)
{
if (_isNull(any)) return "null";
else if (_isUndefined(any)) return "undefined";
else if (_isInfinity(any)) return "infinity";
else if (_isNaN(any)) return "nan";
else if (_isBoolean(any)) return "boolean";
else if (_isNumber(any)) return "number";
else if (_isString(any)) return "string";
else if (_isFunction(any)) return "function";
else if (_isArray(any)) return "array";
else if (_isRegExp(any)) return "regexp";
else if (_isDate(any)) return "date";
return "object";
}
// _toString: Convert any type to a string
//
// Uses native JSON.stringify for objects and arrays when possible
// Note: The JSON spec indicates that NaN stringifies to "null". The reasoning is pretty weak,
// (NaN isn't a keyword). This method is consistent with that behavior (yay standards) but it will be less clear
// when outputting NaN what is going on.
var _toString = function(any)
{
var out = "";
var type = _typeOf(any);
var i;
switch (type)
{
case "null": return "null";
case "undefined": return "undefined";
case "nan": return "NaN";
case "infinity": return "infinity";
case "boolean": // fallthrough
case "number": return String(any);
case "string": return any;
case "regexp": // fallthrough
case "date": return any.toString();
case "element": return "<" + type.nodeName.toLowerCase() + ">";
case "jquery":
// Recurse through elements
var domList = any.get();
for (i = 0; i < domList.length; i++)
out += (i === 0 ? "" : ", ") + arguments.callee(domList[i]);
return "[" + out + "]";
case "object":
// Use native JSON object
if (JSON && _isFunction(JSON.stringify))
return JSON.stringify(any);
// Use toString method
return any.toString();
case "array":
// Use JSON if possible
if (JSON && _isFunction(JSON.stringify))
return JSON.stringify(any);
// Recurse through array
for (i = 0; i < any.length; i++)
out += (i === 0 ? "" : ",") + arguments.callee(any[i]);
return "[" + out + "]";
}
}
// _format: Format complex strings with an object
//
// Example: _format("Hi {name}, see you at {time}{ampm}!", {name:"Jeremy", time:6, ampm:"pm"})
// Returns "Hi Jermey, see you at 6pm!"
//
var _format = function(format, mapping)
{
// Return input without change if it is not a string
if (format == null || typeof (format) != "string" || typeof (mapping) != "object")
return format;
for (var key in mapping)
{
var value = _toString(mapping[key]);
if (typeof (value) != "string")
continue;
// Add braces if not specified
if (key.charAt(0) != "{" && key.charAt(key.length - 1) != "}")
key = "\\{" + key + "\\}";
// Replace key for value
var rx = new RegExp(key, "g");
format = format.replace(rx, value);
}
return format;
}
// _functionName: What is the name of the function?
var _functionName = function (fn) {
var out = fn.toString().match(/function\s*([\w\$]*)\s*\(/);
return out ? out[1] : "function";
};
////////////////////////////////////////////////////////////////////////////
// uno function
////////////////////////////////////////////////////////////////////////////
var defaults = {
group: "Uno",
name: "{method}{args} == {expected}",
object: null,
method: null,
args: null,
expected: null,
result: null
}
var _settings = {}
_extend(_settings, defaults)
uno = function ()
{
// Type signature Count Example
// ANY, ANY 2 uno(Math.pi, 3.14) (Not implemented)
// string, ANY, ANY 3 uno("Math.pi == {expected}", Math.pi, 3.14) (Not implemented)
// function, array, ANY 3 uno(sum, [1,2,3], 6)
// string, function, array, ANY 4 uno("sum{args} == {expected}", sum, [1,2,3], 6)
// object, function, array, ANY 4 uno(person, person.name, [], "Steve")
// string, object, function, array, ANY 5 uno("person.name == {expected}", person, person.name, [], "Steve");
// Interpret arguments
var a = arguments;
var len = a.length;
var i = 0;
// Argument `name` (optional)
var name = _isString(a[i]) ? a[i++] : "{method}({args}) == {expected}";
// Argument `object` (optional)
var object = typeof a[i] === "object" ? a[i++] : null;
// Argument `function` (not optional)
var fn = a[i]
if(!_isFunction(fn))
throw "Uno argument error: `fn` is missing or not a function";
// Argument `args` (not optional)
var args = a[i+1]
if(!_isArray(args))
throw "Uno argument error: `args` is missing or not an [array]";
// Argument `expected` (not optional)
var expected = a[i+2]
// Argument `count` (optional)
var count = a[i+3]
if(!(count === undefined || _isNumber(count)))
throw "Uno argument error: `count` should be an integer or undefined"
// Fail if arguments are invalid
if (len < 3 || len > 5 || !name || !fn || !args)
throw "Uno arguments are invalid";
// Determine if type is simple
var _isSimpleType = function(any){
switch(_typeOf(any)){
case "string": case "null": case "undefined": case "number": case "boolean":
return true;
}
return false;
}
// Test
var result = null;
var isCaught = false;
try { result = fn.apply(object, args); }
catch (e) { result = e; isCaught = true; }
// Name
var map = {};
map.input = map["in"] = map.args = map.arguments = _toString(args).slice(1, -1);
map.output = map["out"] = map.result = _toString(result);
map.method = map.fn = map.f = map["function"] = _functionName(fn);
map.expected = _toString(expected);
name = _format(name, map);
// Message
var pass = _isSame(result, expected);
var message = pass ? "Uno test passed: " + name : "Test failed: " + name
+ "\n input:\t" + map.args
+ "\n " + (isCaught ? "threw:\t" : "returned:\t") + map.result
+ "\n expected:\t" + map.expected + "\n";
// Report to console
var type = pass ? "log" : "error"
if (typeof console[type] !== "undefined")
console[type](message);
// Report to fireunit
if (typeof (fireunit) === "object")
{
// if (pass !== true && _isSimpleType(result) && _isSimpleType(expected))
// fireunit.compare(result, expected, message);
// else
fireunit.ok(pass, message);
}
// Report to QUnit
if (typeof QUnit !== "undefined" && typeof test !== "undefined")
{
}
// Report to JSUnit
if (typeof assertEquals !== "undefined")
{
window["test" + name] = function () {
assertEquals(name, expected, result);
};
}
return pass;
};
////////////////////////////////////////////////////////////////////////////
// uno object
////////////////////////////////////////////////////////////////////////////
// Save version
uno.VERSION = VERSION;
// No conflict
uno.noConflict = function() {
root.uno = previous;
return this;
};
// Private store for user settings
uno._settings = _settings
// Private store to reset user settings
uno._defaults = _defaults
uno.set = function (options) {
_extend(uno._settings, options)
return uno;
}
uno.clearAll = function (options) {
uno._settings = {}
_extend(uno._settings, uno._defaults)
return uno;
}
// Export uno for Node.js
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = uno;
}
exports.uno = uno;
}
// Export uno globally for browser
else {
root['uno'] = uno;
}
})();