forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.js
497 lines (410 loc) · 14 KB
/
common.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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
'use strict';
/***
* @package Common
* @description Internal utility and common methods.
***/
// A few optimizations for Google Closure Compiler will save us a couple kb in the release script.
var object = Object, array = Array, regexp = RegExp, date = Date, string = String, number = Number, func = Function, math = Math, Undefined;
var sugarObject = Sugar.Object, sugarArray = Sugar.Array, sugarDate = Sugar.Date, sugarString = Sugar.String, sugarNumber = Sugar.Number;
// Internal toString
var internalToString = object.prototype.toString;
// Are regexes type function?
var regexIsFunction = typeof regexp() === 'function';
// Do strings have no keys?
var noKeysInStringObjects = !('0' in new string('a'));
// Type check methods need a way to be accessed dynamically.
var typeChecks = {};
// Classes that can be matched by value
var matchedByValueReg = /^\[object Date|Array|String|Number|RegExp|Boolean|Arguments\]$/;
var isBoolean = buildPrimitiveClassCheck('boolean', natives[0]);
var isNumber = buildPrimitiveClassCheck('number', natives[1]);
var isString = buildPrimitiveClassCheck('string', natives[2]);
var isArray = buildClassCheck(natives[3]);
var isDate = buildClassCheck(natives[4]);
var isRegExp = buildClassCheck(natives[5]);
// Wanted to enhance performance here by using simply "typeof"
// but Firefox has two major issues that make this impossible,
// one fixed, the other not. Despite being typeof "function"
// the objects below still report in as [object Function], so
// we need to perform a full class check here.
//
// 1. Regexes can be typeof "function" in FF < 3
// https://bugzilla.mozilla.org/show_bug.cgi?id=61911 (fixed)
//
// 2. HTMLEmbedElement and HTMLObjectElement are be typeof "function"
// https://bugzilla.mozilla.org/show_bug.cgi?id=268945 (won't fix)
//
var isFunction = buildClassCheck(natives[6]);
function isClass(obj, klass, cached) {
var k = cached || className(obj);
return k === '[object '+klass+']';
}
function buildClassCheck(klass) {
var fn = (klass === 'Array' && array.isArray) || function(obj, cached) {
return isClass(obj, klass, cached);
};
typeChecks[klass] = fn;
return fn;
}
function buildPrimitiveClassCheck(type, klass) {
var fn = function(obj) {
if(isObjectType(obj)) {
return isClass(obj, klass);
}
return typeof obj === type;
}
typeChecks[klass] = fn;
return fn;
}
function className(obj) {
return internalToString.call(obj);
}
function extendSimilar(klass, set, fn, instance, polyfill, override) {
var methods = {};
set = isString(set) ? set.split(',') : set;
set.forEach(function(name, i) {
fn(methods, name, i);
});
extend(klass, methods, instance, polyfill, override);
}
// Argument helpers
function isArgumentsObject(obj) {
// .callee exists on Arguments objects in < IE8
return hasProperty(obj, 'length') && (className(obj) === '[object Arguments]' || !!obj.callee);
}
function multiArgs(args, fn, from) {
var result = [], i = from || 0, len;
for(len = args.length; i < len; i++) {
result.push(args[i]);
if(fn) fn.call(args, args[i], i);
}
return result;
}
function flattenedArgs(args, fn, from) {
var arg = args[from || 0];
if(isArray(arg)) {
args = arg;
from = 0;
}
return multiArgs(args, fn, from);
}
function checkCallback(fn) {
if(!fn || !fn.call) {
throw new TypeError('Callback is not callable');
}
}
// General helpers
function isDefined(o) {
return o !== Undefined;
}
function isUndefined(o) {
return o === Undefined;
}
// Object helpers
function hasProperty(obj, prop) {
return !isPrimitiveType(obj) && prop in obj;
}
function isObjectType(obj) {
// 1. Check for null
// 2. Check for regexes in environments where they are "functions".
return !!obj && (typeof obj === 'object' || (regexIsFunction && isRegExp(obj)));
}
function isPrimitiveType(obj) {
var type = typeof obj;
return obj == null || type === 'string' || type === 'number' || type === 'boolean';
}
function isPlainObject(obj, klass) {
klass = klass || className(obj);
try {
// Not own constructor property must be Object
// This code was borrowed from jQuery.isPlainObject
if (obj && obj.constructor &&
!hasOwnProperty(obj, 'constructor') &&
!hasOwnProperty(obj.constructor.prototype, 'isPrototypeOf')) {
return false;
}
} catch (e) {
// IE8,9 Will throw exceptions on certain host objects.
return false;
}
// === on the constructor is not safe across iframes
// 'hasOwnProperty' ensures that the object also inherits
// from Object, which is false for DOMElements in IE.
return !!obj && klass === '[object Object]' && 'hasOwnProperty' in obj;
}
function simpleRepeat(n, fn) {
for(var i = 0; i < n; i++) {
fn(i);
}
}
function simpleMerge(target, source) {
iterateOverObject(source, function(key) {
target[key] = source[key];
});
return target;
}
// Make primtives types like strings into objects.
function coercePrimitiveToObject(obj) {
if(isPrimitiveType(obj)) {
obj = object(obj);
}
if(noKeysInStringObjects && isString(obj)) {
forceStringCoercion(obj);
}
return obj;
}
// Force strings to have their indexes set in
// environments that don't do this automatically.
function forceStringCoercion(obj) {
var i = 0, chr;
while(chr = obj.charAt(i)) {
obj[i++] = chr;
}
}
// Hash definition
function Hash(obj) {
simpleMerge(this, coercePrimitiveToObject(obj));
};
Hash.prototype.constructor = object;
// Math helpers
var abs = math.abs;
var pow = math.pow;
var ceil = math.ceil;
var floor = math.floor;
var round = math.round;
var min = math.min;
var max = math.max;
function withPrecision(val, precision, fn) {
var multiplier = pow(10, abs(precision || 0));
fn = fn || round;
if(precision < 0) multiplier = 1 / multiplier;
return fn(val * multiplier) / multiplier;
}
// Full width number helpers
var HalfWidthZeroCode = 0x30;
var HalfWidthNineCode = 0x39;
var FullWidthZeroCode = 0xff10;
var FullWidthNineCode = 0xff19;
var HalfWidthPeriod = '.';
var FullWidthPeriod = '.';
var HalfWidthComma = ',';
// Used here and later in the Date package.
var FullWidthDigits = '';
var NumberNormalizeMap = {};
var NumberNormalizeReg;
function codeIsNumeral(code) {
return (code >= HalfWidthZeroCode && code <= HalfWidthNineCode) ||
(code >= FullWidthZeroCode && code <= FullWidthNineCode);
}
function buildNumberHelpers() {
var digit, i;
for(i = 0; i <= 9; i++) {
digit = chr(i + FullWidthZeroCode);
FullWidthDigits += digit;
NumberNormalizeMap[digit] = chr(i + HalfWidthZeroCode);
}
NumberNormalizeMap[HalfWidthComma] = '';
NumberNormalizeMap[FullWidthPeriod] = HalfWidthPeriod;
// Mapping this to itself to easily be able to easily
// capture it in stringToNumber to detect decimals later.
NumberNormalizeMap[HalfWidthPeriod] = HalfWidthPeriod;
NumberNormalizeReg = regexp('[' + FullWidthDigits + FullWidthPeriod + HalfWidthComma + HalfWidthPeriod + ']', 'g');
}
// String helpers
function chr(num) {
return string.fromCharCode(num);
}
// WhiteSpace/LineTerminator as defined in ES5.1 plus Unicode characters in the Space, Separator category.
function getTrimmableCharacters() {
return '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
}
function repeatString(str, num) {
var result = '';
str = str.toString();
while (num > 0) {
if (num & 1) {
result += str;
}
if (num >>= 1) {
str += str;
}
}
return result;
}
// Returns taking into account full-width characters, commas, and decimals.
function stringToNumber(str, base) {
var sanitized, isDecimal;
sanitized = str.replace(NumberNormalizeReg, function(chr) {
var replacement = NumberNormalizeMap[chr];
if(replacement === HalfWidthPeriod) {
isDecimal = true;
}
return replacement;
});
return isDecimal ? parseFloat(sanitized) : parseInt(sanitized, base || 10);
}
// Used by Number and Date
function padNumber(num, place, sign, base) {
var str = abs(num).toString(base || 10);
str = repeatString('0', place - str.replace(/\.\d+/, '').length) + str;
if(sign || num < 0) {
str = (num < 0 ? '-' : '+') + str;
}
return str;
}
function getOrdinalizedSuffix(num) {
if(num >= 11 && num <= 13) {
return 'th';
} else {
switch(num % 10) {
case 1: return 'st';
case 2: return 'nd';
case 3: return 'rd';
default: return 'th';
}
}
}
// RegExp helpers
function getRegExpFlags(reg, add) {
var flags = '';
add = add || '';
function checkFlag(prop, flag) {
if(prop || add.indexOf(flag) > -1) {
flags += flag;
}
}
checkFlag(reg.multiline, 'm');
checkFlag(reg.ignoreCase, 'i');
checkFlag(reg.global, 'g');
checkFlag(reg.sticky, 'y');
return flags;
}
function escapeRegExp(str) {
if(!isString(str)) str = string(str);
return str.replace(/([\\\/\'*+?|()\[\]{}.^$-])/g,'\\$1');
}
// Date helpers
function callDateGet(d, method) {
return d['get' + (d._utc ? 'UTC' : '') + method]();
}
function callDateSet(d, method, value) {
return d['set' + (d._utc ? 'UTC' : '') + method](value);
}
// Used by Array#unique and Object.equal
function stringify(thing, stack) {
var type = typeof thing,
thingIsObject,
thingIsArray,
klass, value,
arr, key, i, len;
// Return quickly if string to save cycles
if(type === 'string') return thing;
klass = internalToString.call(thing);
thingIsObject = isPlainObject(thing, klass);
thingIsArray = isArray(thing, klass);
if(thing != null && thingIsObject || thingIsArray) {
// This method for checking for cyclic structures was egregiously stolen from
// the ingenious method by @kitcambridge from the Underscore script:
// https://github.com/documentcloud/underscore/issues/240
if(!stack) stack = [];
// Allowing a step into the structure before triggering this
// script to save cycles on standard JSON structures and also to
// try as hard as possible to catch basic properties that may have
// been modified.
if(stack.length > 1) {
i = stack.length;
while (i--) {
if (stack[i] === thing) {
return 'CYC';
}
}
}
stack.push(thing);
value = thing.valueOf() + string(thing.constructor);
arr = thingIsArray ? thing : object.keys(thing).sort();
for(i = 0, len = arr.length; i < len; i++) {
key = thingIsArray ? i : arr[i];
value += key + stringify(thing[key], stack);
}
stack.pop();
} else if(1 / thing === -Infinity) {
value = '-0';
} else {
value = string(thing && thing.valueOf ? thing.valueOf() : thing);
}
return type + klass + value;
}
function isEqual(a, b) {
if(a === b) {
// Return quickly up front when matching by reference,
// but be careful about 0 !== -0.
return a !== 0 || 1 / a === 1 / b;
} else if(objectIsMatchedByValue(a) && objectIsMatchedByValue(b)) {
return stringify(a) === stringify(b);
}
return false;
}
function objectIsMatchedByValue(obj) {
// Only known objects are matched by value. This is notably excluding functions, DOM Elements, and instances of
// user-created classes. The latter can arguably be matched by value, but distinguishing between these and
// host objects -- which should never be compared by value -- is very tricky so not dealing with it here.
var klass = className(obj);
return matchedByValueReg.test(klass) || isPlainObject(obj, klass);
}
// Used by Array#at and String#at
function getEntriesForIndexes(obj, args, isString) {
var result,
length = obj.length,
argsLen = args.length,
overshoot = args[argsLen - 1] !== false,
multiple = argsLen > (overshoot ? 1 : 2);
if(!multiple) {
return entryAtIndex(obj, length, args[0], overshoot, isString);
}
result = [];
multiArgs(args, function(index) {
if(isBoolean(index)) return false;
result.push(entryAtIndex(obj, length, index, overshoot, isString));
});
return result;
}
function entryAtIndex(obj, length, index, overshoot, isString) {
if(overshoot) {
index = index % length;
if(index < 0) index = length + index;
}
return isString ? obj.charAt(index) : obj[index];
}
// Used by the Array and Object packages.
function transformArgument(el, map, context, mapArgs) {
if(!map) {
return el;
} else if(map.apply) {
return map.apply(context, mapArgs || []);
} else if(isFunction(el[map])) {
return el[map].call(el);
} else {
return el[map];
}
}
function keysWithObjectCoercion(obj) {
return object.keys(coercePrimitiveToObject(obj));
}
// Object class methods implemented as instance methods. This method
// is being called only on Hash and Object itself, so we don't want
// to go through extend() here as it will create proxies that already
// exist, which we want to avoid.
function buildObjectInstanceMethods(set, target) {
set.forEach(function(name) {
var classFn = sugarObject[name === 'equals' ? 'equal' : name];
var fn = function() {
var args = arguments, newArgs = [this], i;
for(i = 0;i < args.length;i++) {
newArgs.push(args[i]);
}
return classFn.apply(null, newArgs);
}
setProperty(target.prototype, name, fn);
});
}
buildNumberHelpers();