2 * https://github.com/es-shims/es5-shim
3 * @license es5-shim Copyright 2009-2015 by contributors, MIT License
4 * see https://github.com/es-shims/es5-shim/blob/master/LICENSE
7 // vim: ts=4 sts=4 sw=4 expandtab
9 // Add semicolon to prevent IIFE from being passed as argument to concatenated code.
12 // UMD (Universal Module Definition)
13 // see https://github.com/umdjs/umd/blob/master/templates/returnExports.js
14 (function (root, factory) {
17 /* global define, exports, module */
18 if (typeof define === 'function' && define.amd) {
19 // AMD. Register as an anonymous module.
21 } else if (typeof exports === 'object') {
22 // Node. Does not work with strict CommonJS, but
23 // only CommonJS-like enviroments that support module.exports,
25 module.exports = factory();
27 // Browser globals (root is window)
28 root.returnExports = factory();
32 * Brings an environment as close to ECMAScript 5 compliance
33 * as is possible with the facilities of erstwhile engines.
35 * Annotated ES5: http://es5.github.com/ (specific links below)
36 * ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
37 * Required reading: http://javascriptweblog.wordpress.com/2011/12/05/extending-javascript-natives/
40 // Shortcut to an often accessed properties, in order to avoid multiple
41 // dereference that costs universally. This also holds a reference to known-good
44 var ArrayPrototype = $Array.prototype;
46 var ObjectPrototype = $Object.prototype;
47 var $Function = Function;
48 var FunctionPrototype = $Function.prototype;
50 var StringPrototype = $String.prototype;
52 var NumberPrototype = $Number.prototype;
53 var array_slice = ArrayPrototype.slice;
54 var array_splice = ArrayPrototype.splice;
55 var array_push = ArrayPrototype.push;
56 var array_unshift = ArrayPrototype.unshift;
57 var array_concat = ArrayPrototype.concat;
58 var array_join = ArrayPrototype.join;
59 var call = FunctionPrototype.call;
60 var apply = FunctionPrototype.apply;
64 // Having a toString local variable name breaks in Opera so use to_string.
65 var to_string = ObjectPrototype.toString;
68 /* eslint-disable one-var-declaration-per-line, no-redeclare, max-statements-per-line */
69 var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol';
70 var isCallable; /* inlined from https://npmjs.com/is-callable */ var fnToStr = Function.prototype.toString, constructorRegex = /^\s*class /, isES6ClassFn = function isES6ClassFn(value) { try { var fnStr = fnToStr.call(value); var singleStripped = fnStr.replace(/\/\/.*\n/g, ''); var multiStripped = singleStripped.replace(/\/\*[.\s\S]*\*\//g, ''); var spaceStripped = multiStripped.replace(/\n/mg, ' ').replace(/ {2}/g, ' '); return constructorRegex.test(spaceStripped); } catch (e) { return false; /* not a function */ } }, tryFunctionObject = function tryFunctionObject(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }, fnClass = '[object Function]', genClass = '[object GeneratorFunction]', isCallable = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = to_string.call(value); return strClass === fnClass || strClass === genClass; };
72 var isRegex; /* inlined from https://npmjs.com/is-regex */ var regexExec = RegExp.prototype.exec, tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }, regexClass = '[object RegExp]'; isRegex = function isRegex(value) { if (typeof value !== 'object') { return false; } return hasToStringTag ? tryRegexExec(value) : to_string.call(value) === regexClass; };
73 var isString; /* inlined from https://npmjs.com/is-string */ var strValue = String.prototype.valueOf, tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }, stringClass = '[object String]'; isString = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : to_string.call(value) === stringClass; };
74 /* eslint-enable one-var-declaration-per-line, no-redeclare, max-statements-per-line */
76 /* inlined from http://npmjs.com/define-properties */
77 var supportsDescriptors = $Object.defineProperty && (function () {
80 $Object.defineProperty(obj, 'x', { enumerable: false, value: obj });
81 for (var _ in obj) { // jscs:ignore disallowUnusedVariables
85 } catch (e) { /* this is ES3 */
89 var defineProperties = (function (has) {
90 // Define configurable, writable, and non-enumerable props
91 // if they don't exist.
93 if (supportsDescriptors) {
94 defineProperty = function (object, name, method, forceAssign) {
95 if (!forceAssign && (name in object)) {
98 $Object.defineProperty(object, name, {
106 defineProperty = function (object, name, method, forceAssign) {
107 if (!forceAssign && (name in object)) {
110 object[name] = method;
113 return function defineProperties(object, map, forceAssign) {
114 for (var name in map) {
115 if (has.call(map, name)) {
116 defineProperty(object, name, map[name], forceAssign);
120 }(ObjectPrototype.hasOwnProperty));
127 /* replaceable with https://npmjs.com/package/es-abstract /helpers/isPrimitive */
128 var isPrimitive = function isPrimitive(input) {
129 var type = typeof input;
130 return input === null || (type !== 'object' && type !== 'function');
133 var isActualNaN = $Number.isNaN || function isActualNaN(x) {
139 // http://es5.github.com/#x9.4
140 // http://jsperf.com/to-integer
141 /* replaceable with https://npmjs.com/package/es-abstract ES5.ToInteger */
142 ToInteger: function ToInteger(num) {
144 if (isActualNaN(n)) {
146 } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
147 n = (n > 0 || -1) * Math.floor(Math.abs(n));
152 /* replaceable with https://npmjs.com/package/es-abstract ES5.ToPrimitive */
153 ToPrimitive: function ToPrimitive(input) {
154 var val, valueOf, toStr;
155 if (isPrimitive(input)) {
158 valueOf = input.valueOf;
159 if (isCallable(valueOf)) {
160 val = valueOf.call(input);
161 if (isPrimitive(val)) {
165 toStr = input.toString;
166 if (isCallable(toStr)) {
167 val = toStr.call(input);
168 if (isPrimitive(val)) {
172 throw new TypeError();
176 // http://es5.github.com/#x9.9
177 /* replaceable with https://npmjs.com/package/es-abstract ES5.ToObject */
178 ToObject: function (o) {
179 if (o == null) { // this matches both null and undefined
180 throw new TypeError("can't convert " + o + ' to object');
185 /* replaceable with https://npmjs.com/package/es-abstract ES5.ToUint32 */
186 ToUint32: function ToUint32(x) {
197 // http://es5.github.com/#x15.3.4.5
199 var Empty = function Empty() {};
201 defineProperties(FunctionPrototype, {
202 bind: function bind(that) { // .length is 1
203 // 1. Let Target be the this value.
205 // 2. If IsCallable(Target) is false, throw a TypeError exception.
206 if (!isCallable(target)) {
207 throw new TypeError('Function.prototype.bind called on incompatible ' + target);
209 // 3. Let A be a new (possibly empty) internal list of all of the
210 // argument values provided after thisArg (arg1, arg2 etc), in order.
211 // XXX slicedArgs will stand in for "A" if used
212 var args = array_slice.call(arguments, 1); // for normal call
213 // 4. Let F be a new native ECMAScript object.
214 // 11. Set the [[Prototype]] internal property of F to the standard
215 // built-in Function prototype object as specified in 15.3.3.1.
216 // 12. Set the [[Call]] internal property of F as described in
218 // 13. Set the [[Construct]] internal property of F as described in
220 // 14. Set the [[HasInstance]] internal property of F as described in
223 var binder = function () {
225 if (this instanceof bound) {
226 // 15.3.4.5.2 [[Construct]]
227 // When the [[Construct]] internal method of a function object,
228 // F that was created using the bind function is called with a
229 // list of arguments ExtraArgs, the following steps are taken:
230 // 1. Let target be the value of F's [[TargetFunction]]
231 // internal property.
232 // 2. If target has no [[Construct]] internal method, a
233 // TypeError exception is thrown.
234 // 3. Let boundArgs be the value of F's [[BoundArgs]] internal
236 // 4. Let args be a new list containing the same values as the
237 // list boundArgs in the same order followed by the same
238 // values as the list ExtraArgs in the same order.
239 // 5. Return the result of calling the [[Construct]] internal
240 // method of target providing args as the arguments.
242 var result = apply.call(
245 array_concat.call(args, array_slice.call(arguments))
247 if ($Object(result) === result) {
253 // 15.3.4.5.1 [[Call]]
254 // When the [[Call]] internal method of a function object, F,
255 // which was created using the bind function is called with a
256 // this value and a list of arguments ExtraArgs, the following
258 // 1. Let boundArgs be the value of F's [[BoundArgs]] internal
260 // 2. Let boundThis be the value of F's [[BoundThis]] internal
262 // 3. Let target be the value of F's [[TargetFunction]] internal
264 // 4. Let args be a new list containing the same values as the
265 // list boundArgs in the same order followed by the same
266 // values as the list ExtraArgs in the same order.
267 // 5. Return the result of calling the [[Call]] internal method
268 // of target providing boundThis as the this value and
269 // providing args as the arguments.
271 // equiv: target.call(this, ...boundArgs, ...args)
275 array_concat.call(args, array_slice.call(arguments))
282 // 15. If the [[Class]] internal property of Target is "Function", then
283 // a. Let L be the length property of Target minus the length of A.
284 // b. Set the length own property of F to either 0 or L, whichever is
286 // 16. Else set the length own property of F to 0.
288 var boundLength = max(0, target.length - args.length);
290 // 17. Set the attributes of the length own property of F to the values
291 // specified in 15.3.5.1.
293 for (var i = 0; i < boundLength; i++) {
294 array_push.call(boundArgs, '$' + i);
297 // XXX Build a dynamic function with desired amount of arguments is the only
298 // way to set the length property of a function.
299 // In environments where Content Security Policies enabled (Chrome extensions,
300 // for ex.) all use of eval or Function costructor throws an exception.
301 // However in all of these environments Function.prototype.bind exists
302 // and so this code will never be executed.
303 bound = $Function('binder', 'return function (' + array_join.call(boundArgs, ',') + '){ return binder.apply(this, arguments); }')(binder);
305 if (target.prototype) {
306 Empty.prototype = target.prototype;
307 bound.prototype = new Empty();
308 // Clean up dangling references.
309 Empty.prototype = null;
313 // 18. Set the [[Extensible]] internal property of F to true.
316 // 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
317 // 20. Call the [[DefineOwnProperty]] internal method of F with
318 // arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
319 // thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
321 // 21. Call the [[DefineOwnProperty]] internal method of F with
322 // arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
323 // [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
327 // NOTE Function objects created using Function.prototype.bind do not
328 // have a prototype property or the [[Code]], [[FormalParameters]], and
329 // [[Scope]] internal properties.
330 // XXX can't delete prototype in pure-js.
337 // _Please note: Shortcuts are defined after `Function.prototype.bind` as we
338 // use it in defining shortcuts.
339 var owns = call.bind(ObjectPrototype.hasOwnProperty);
340 var toStr = call.bind(ObjectPrototype.toString);
341 var arraySlice = call.bind(array_slice);
342 var arraySliceApply = apply.bind(array_slice);
343 var strSlice = call.bind(StringPrototype.slice);
344 var strSplit = call.bind(StringPrototype.split);
345 var strIndexOf = call.bind(StringPrototype.indexOf);
346 var pushCall = call.bind(array_push);
347 var isEnum = call.bind(ObjectPrototype.propertyIsEnumerable);
348 var arraySort = call.bind(ArrayPrototype.sort);
355 var isArray = $Array.isArray || function isArray(obj) {
356 return toStr(obj) === '[object Array]';
360 // http://es5.github.com/#x15.4.4.13
361 // Return len+argCount.
363 // IE < 8 bug: [].unshift(0) === undefined but should be "1"
364 var hasUnshiftReturnValueBug = [].unshift(0) !== 1;
365 defineProperties(ArrayPrototype, {
366 unshift: function () {
367 array_unshift.apply(this, arguments);
370 }, hasUnshiftReturnValueBug);
373 // http://es5.github.com/#x15.4.3.2
374 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
375 defineProperties($Array, { isArray: isArray });
377 // The IsCallable() check in the Array functions
378 // has been replaced with a strict check on the
379 // internal class of the object to trap cases where
380 // the provided function was actually a regular
381 // expression literal, which in V8 and
382 // JavaScriptCore is a typeof "function". Only in
383 // V8 are regular expression literals permitted as
384 // reduce parameters, so it is desirable in the
385 // general case for the shim to match the more
386 // strict and common behavior of rejecting regular
390 // http://es5.github.com/#x15.4.4.18
391 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
393 // Check failure of by-index access of string characters (IE < 9)
394 // and failure of `0 in boxedString` (Rhino)
395 var boxedString = $Object('a');
396 var splitString = boxedString[0] !== 'a' || !(0 in boxedString);
398 var properlyBoxesContext = function properlyBoxed(method) {
399 // Check node 0.6.21 bug where third parameter is not boxed
400 var properlyBoxesNonStrict = true;
401 var properlyBoxesStrict = true;
402 var threwException = false;
405 method.call('foo', function (_, __, context) {
406 if (typeof context !== 'object') {
407 properlyBoxesNonStrict = false;
411 method.call([1], function () {
414 properlyBoxesStrict = typeof this === 'string';
417 threwException = true;
420 return !!method && !threwException && properlyBoxesNonStrict && properlyBoxesStrict;
423 defineProperties(ArrayPrototype, {
424 forEach: function forEach(callbackfn/*, thisArg*/) {
425 var object = ES.ToObject(this);
426 var self = splitString && isString(this) ? strSplit(this, '') : object;
428 var length = ES.ToUint32(self.length);
430 if (arguments.length > 1) {
434 // If no callback function or if callback is not a callable function
435 if (!isCallable(callbackfn)) {
436 throw new TypeError('Array.prototype.forEach callback must be a function');
439 while (++i < length) {
441 // Invoke the callback function with call, passing arguments:
442 // context, property value, property key, thisArg object
443 if (typeof T === 'undefined') {
444 callbackfn(self[i], i, object);
446 callbackfn.call(T, self[i], i, object);
451 }, !properlyBoxesContext(ArrayPrototype.forEach));
454 // http://es5.github.com/#x15.4.4.19
455 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
456 defineProperties(ArrayPrototype, {
457 map: function map(callbackfn/*, thisArg*/) {
458 var object = ES.ToObject(this);
459 var self = splitString && isString(this) ? strSplit(this, '') : object;
460 var length = ES.ToUint32(self.length);
461 var result = $Array(length);
463 if (arguments.length > 1) {
467 // If no callback function or if callback is not a callable function
468 if (!isCallable(callbackfn)) {
469 throw new TypeError('Array.prototype.map callback must be a function');
472 for (var i = 0; i < length; i++) {
474 if (typeof T === 'undefined') {
475 result[i] = callbackfn(self[i], i, object);
477 result[i] = callbackfn.call(T, self[i], i, object);
483 }, !properlyBoxesContext(ArrayPrototype.map));
486 // http://es5.github.com/#x15.4.4.20
487 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
488 defineProperties(ArrayPrototype, {
489 filter: function filter(callbackfn/*, thisArg*/) {
490 var object = ES.ToObject(this);
491 var self = splitString && isString(this) ? strSplit(this, '') : object;
492 var length = ES.ToUint32(self.length);
496 if (arguments.length > 1) {
500 // If no callback function or if callback is not a callable function
501 if (!isCallable(callbackfn)) {
502 throw new TypeError('Array.prototype.filter callback must be a function');
505 for (var i = 0; i < length; i++) {
508 if (typeof T === 'undefined' ? callbackfn(value, i, object) : callbackfn.call(T, value, i, object)) {
509 pushCall(result, value);
515 }, !properlyBoxesContext(ArrayPrototype.filter));
518 // http://es5.github.com/#x15.4.4.16
519 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
520 defineProperties(ArrayPrototype, {
521 every: function every(callbackfn/*, thisArg*/) {
522 var object = ES.ToObject(this);
523 var self = splitString && isString(this) ? strSplit(this, '') : object;
524 var length = ES.ToUint32(self.length);
526 if (arguments.length > 1) {
530 // If no callback function or if callback is not a callable function
531 if (!isCallable(callbackfn)) {
532 throw new TypeError('Array.prototype.every callback must be a function');
535 for (var i = 0; i < length; i++) {
536 if (i in self && !(typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
542 }, !properlyBoxesContext(ArrayPrototype.every));
545 // http://es5.github.com/#x15.4.4.17
546 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
547 defineProperties(ArrayPrototype, {
548 some: function some(callbackfn/*, thisArg */) {
549 var object = ES.ToObject(this);
550 var self = splitString && isString(this) ? strSplit(this, '') : object;
551 var length = ES.ToUint32(self.length);
553 if (arguments.length > 1) {
557 // If no callback function or if callback is not a callable function
558 if (!isCallable(callbackfn)) {
559 throw new TypeError('Array.prototype.some callback must be a function');
562 for (var i = 0; i < length; i++) {
563 if (i in self && (typeof T === 'undefined' ? callbackfn(self[i], i, object) : callbackfn.call(T, self[i], i, object))) {
569 }, !properlyBoxesContext(ArrayPrototype.some));
572 // http://es5.github.com/#x15.4.4.21
573 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
574 var reduceCoercesToObject = false;
575 if (ArrayPrototype.reduce) {
576 reduceCoercesToObject = typeof ArrayPrototype.reduce.call('es5', function (_, __, ___, list) {
580 defineProperties(ArrayPrototype, {
581 reduce: function reduce(callbackfn/*, initialValue*/) {
582 var object = ES.ToObject(this);
583 var self = splitString && isString(this) ? strSplit(this, '') : object;
584 var length = ES.ToUint32(self.length);
586 // If no callback function or if callback is not a callable function
587 if (!isCallable(callbackfn)) {
588 throw new TypeError('Array.prototype.reduce callback must be a function');
591 // no value to return if no initial value and an empty array
592 if (length === 0 && arguments.length === 1) {
593 throw new TypeError('reduce of empty array with no initial value');
598 if (arguments.length >= 2) {
599 result = arguments[1];
607 // if array contains no values, no initial value to return
609 throw new TypeError('reduce of empty array with no initial value');
614 for (; i < length; i++) {
616 result = callbackfn(result, self[i], i, object);
622 }, !reduceCoercesToObject);
625 // http://es5.github.com/#x15.4.4.22
626 // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
627 var reduceRightCoercesToObject = false;
628 if (ArrayPrototype.reduceRight) {
629 reduceRightCoercesToObject = typeof ArrayPrototype.reduceRight.call('es5', function (_, __, ___, list) {
633 defineProperties(ArrayPrototype, {
634 reduceRight: function reduceRight(callbackfn/*, initial*/) {
635 var object = ES.ToObject(this);
636 var self = splitString && isString(this) ? strSplit(this, '') : object;
637 var length = ES.ToUint32(self.length);
639 // If no callback function or if callback is not a callable function
640 if (!isCallable(callbackfn)) {
641 throw new TypeError('Array.prototype.reduceRight callback must be a function');
644 // no value to return if no initial value, empty array
645 if (length === 0 && arguments.length === 1) {
646 throw new TypeError('reduceRight of empty array with no initial value');
651 if (arguments.length >= 2) {
652 result = arguments[1];
660 // if array contains no values, no initial value to return
662 throw new TypeError('reduceRight of empty array with no initial value');
673 result = callbackfn(result, self[i], i, object);
679 }, !reduceRightCoercesToObject);
682 // http://es5.github.com/#x15.4.4.14
683 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
684 var hasFirefox2IndexOfBug = ArrayPrototype.indexOf && [0, 1].indexOf(1, 2) !== -1;
685 defineProperties(ArrayPrototype, {
686 indexOf: function indexOf(searchElement/*, fromIndex */) {
687 var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
688 var length = ES.ToUint32(self.length);
695 if (arguments.length > 1) {
696 i = ES.ToInteger(arguments[1]);
699 // handle negative indices
700 i = i >= 0 ? i : max(0, length + i);
701 for (; i < length; i++) {
702 if (i in self && self[i] === searchElement) {
708 }, hasFirefox2IndexOfBug);
711 // http://es5.github.com/#x15.4.4.15
712 // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
713 var hasFirefox2LastIndexOfBug = ArrayPrototype.lastIndexOf && [0, 1].lastIndexOf(0, -3) !== -1;
714 defineProperties(ArrayPrototype, {
715 lastIndexOf: function lastIndexOf(searchElement/*, fromIndex */) {
716 var self = splitString && isString(this) ? strSplit(this, '') : ES.ToObject(this);
717 var length = ES.ToUint32(self.length);
723 if (arguments.length > 1) {
724 i = min(i, ES.ToInteger(arguments[1]));
726 // handle negative indices
727 i = i >= 0 ? i : length - Math.abs(i);
728 for (; i >= 0; i--) {
729 if (i in self && searchElement === self[i]) {
735 }, hasFirefox2LastIndexOfBug);
738 // http://es5.github.com/#x15.4.4.12
739 var spliceNoopReturnsEmptyArray = (function () {
741 var result = a.splice();
742 return a.length === 2 && isArray(result) && result.length === 0;
744 defineProperties(ArrayPrototype, {
745 // Safari 5.0 bug where .splice() returns undefined
746 splice: function splice(start, deleteCount) {
747 if (arguments.length === 0) {
750 return array_splice.apply(this, arguments);
753 }, !spliceNoopReturnsEmptyArray);
755 var spliceWorksWithEmptyObject = (function () {
757 ArrayPrototype.splice.call(obj, 0, 0, 1);
758 return obj.length === 1;
760 defineProperties(ArrayPrototype, {
761 splice: function splice(start, deleteCount) {
762 if (arguments.length === 0) {
765 var args = arguments;
766 this.length = max(ES.ToInteger(this.length), 0);
767 if (arguments.length > 0 && typeof deleteCount !== 'number') {
768 args = arraySlice(arguments);
769 if (args.length < 2) {
770 pushCall(args, this.length - start);
772 args[1] = ES.ToInteger(deleteCount);
775 return array_splice.apply(this, args);
777 }, !spliceWorksWithEmptyObject);
778 var spliceWorksWithLargeSparseArrays = (function () {
779 // Per https://github.com/es-shims/es5-shim/issues/295
780 // Safari 7/8 breaks with sparse arrays of size 1e5 or greater
781 var arr = new $Array(1e5);
782 // note: the index MUST be 8 or larger or the test will false pass
785 // note: this test must be defined *after* the indexOf shim
786 // per https://github.com/es-shims/es5-shim/issues/313
787 return arr.indexOf('x') === 7;
789 var spliceWorksWithSmallSparseArrays = (function () {
790 // Per https://github.com/es-shims/es5-shim/issues/295
791 // Opera 12.15 breaks on this, no idea why.
795 arr.splice(n + 1, 0, 'b');
796 return arr[n] === 'a';
798 defineProperties(ArrayPrototype, {
799 splice: function splice(start, deleteCount) {
800 var O = ES.ToObject(this);
802 var len = ES.ToUint32(O.length);
803 var relativeStart = ES.ToInteger(start);
804 var actualStart = relativeStart < 0 ? max((len + relativeStart), 0) : min(relativeStart, len);
805 var actualDeleteCount = min(max(ES.ToInteger(deleteCount), 0), len - actualStart);
809 while (k < actualDeleteCount) {
810 from = $String(actualStart + k);
817 var items = arraySlice(arguments, 2);
818 var itemCount = items.length;
820 if (itemCount < actualDeleteCount) {
822 var maxK = len - actualDeleteCount;
824 from = $String(k + actualDeleteCount);
825 to = $String(k + itemCount);
834 var minK = len - actualDeleteCount + itemCount;
839 } else if (itemCount > actualDeleteCount) {
840 k = len - actualDeleteCount;
841 while (k > actualStart) {
842 from = $String(k + actualDeleteCount - 1);
843 to = $String(k + itemCount - 1);
853 for (var i = 0; i < items.length; ++i) {
857 O.length = len - actualDeleteCount + itemCount;
861 }, !spliceWorksWithLargeSparseArrays || !spliceWorksWithSmallSparseArrays);
863 var originalJoin = ArrayPrototype.join;
864 var hasStringJoinBug;
866 hasStringJoinBug = Array.prototype.join.call('123', ',') !== '1,2,3';
868 hasStringJoinBug = true;
870 if (hasStringJoinBug) {
871 defineProperties(ArrayPrototype, {
872 join: function join(separator) {
873 var sep = typeof separator === 'undefined' ? ',' : separator;
874 return originalJoin.call(isString(this) ? strSplit(this, '') : this, sep);
876 }, hasStringJoinBug);
879 var hasJoinUndefinedBug = [1, 2].join(undefined) !== '1,2';
880 if (hasJoinUndefinedBug) {
881 defineProperties(ArrayPrototype, {
882 join: function join(separator) {
883 var sep = typeof separator === 'undefined' ? ',' : separator;
884 return originalJoin.call(this, sep);
886 }, hasJoinUndefinedBug);
889 var pushShim = function push(item) {
890 var O = ES.ToObject(this);
891 var n = ES.ToUint32(O.length);
893 while (i < arguments.length) {
894 O[n + i] = arguments[i];
901 var pushIsNotGeneric = (function () {
903 var result = Array.prototype.push.call(obj, undefined);
904 return result !== 1 || obj.length !== 1 || typeof obj[0] !== 'undefined' || !owns(obj, 0);
906 defineProperties(ArrayPrototype, {
907 push: function push(item) {
909 return array_push.apply(this, arguments);
911 return pushShim.apply(this, arguments);
913 }, pushIsNotGeneric);
915 // This fixes a very weird bug in Opera 10.6 when pushing `undefined
916 var pushUndefinedIsWeird = (function () {
918 var result = arr.push(undefined);
919 return result !== 1 || arr.length !== 1 || typeof arr[0] !== 'undefined' || !owns(arr, 0);
921 defineProperties(ArrayPrototype, { push: pushShim }, pushUndefinedIsWeird);
924 // http://es5.github.io/#x15.4.4.10
925 // Fix boxed string bug
926 defineProperties(ArrayPrototype, {
927 slice: function (start, end) {
928 var arr = isString(this) ? strSplit(this, '') : this;
929 return arraySliceApply(arr, arguments);
933 var sortIgnoresNonFunctions = (function () {
941 var sortThrowsOnRegex = (function () {
942 // this is a problem in Firefox 4, in which `typeof /a/ === 'function'`
949 var sortIgnoresUndefined = (function () {
950 // applies in IE 8, for one.
952 [1, 2].sort(undefined);
957 defineProperties(ArrayPrototype, {
958 sort: function sort(compareFn) {
959 if (typeof compareFn === 'undefined') {
960 return arraySort(this);
962 if (!isCallable(compareFn)) {
963 throw new TypeError('Array.prototype.sort callback must be a function');
965 return arraySort(this, compareFn);
967 }, sortIgnoresNonFunctions || !sortIgnoresUndefined || !sortThrowsOnRegex);
975 // http://es5.github.com/#x15.2.3.14
977 // http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
978 var hasDontEnumBug = !isEnum({ 'toString': null }, 'toString');
979 var hasProtoEnumBug = isEnum(function () {}, 'prototype');
980 var hasStringEnumBug = !owns('x', '0');
981 var equalsConstructorPrototype = function (o) {
982 var ctor = o.constructor;
983 return ctor && ctor.prototype === o;
985 var blacklistedKeys = {
993 $webkitIndexedDB: true,
994 $webkitStorageInfo: true,
997 var hasAutomationEqualityBug = (function () {
999 if (typeof window === 'undefined') {
1002 for (var k in window) {
1004 if (!blacklistedKeys['$' + k] && owns(window, k) && window[k] !== null && typeof window[k] === 'object') {
1005 equalsConstructorPrototype(window[k]);
1013 var equalsConstructorPrototypeIfNotBuggy = function (object) {
1014 if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
1015 return equalsConstructorPrototype(object);
1018 return equalsConstructorPrototype(object);
1029 'propertyIsEnumerable',
1032 var dontEnumsLength = dontEnums.length;
1034 // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js
1035 // can be replaced with require('is-arguments') if we ever use a build process instead
1036 var isStandardArguments = function isArguments(value) {
1037 return toStr(value) === '[object Arguments]';
1039 var isLegacyArguments = function isArguments(value) {
1040 return value !== null &&
1041 typeof value === 'object' &&
1042 typeof value.length === 'number' &&
1043 value.length >= 0 &&
1045 isCallable(value.callee);
1047 var isArguments = isStandardArguments(arguments) ? isStandardArguments : isLegacyArguments;
1049 defineProperties($Object, {
1050 keys: function keys(object) {
1051 var isFn = isCallable(object);
1052 var isArgs = isArguments(object);
1053 var isObject = object !== null && typeof object === 'object';
1054 var isStr = isObject && isString(object);
1056 if (!isObject && !isFn && !isArgs) {
1057 throw new TypeError('Object.keys called on a non-object');
1061 var skipProto = hasProtoEnumBug && isFn;
1062 if ((isStr && hasStringEnumBug) || isArgs) {
1063 for (var i = 0; i < object.length; ++i) {
1064 pushCall(theKeys, $String(i));
1069 for (var name in object) {
1070 if (!(skipProto && name === 'prototype') && owns(object, name)) {
1071 pushCall(theKeys, $String(name));
1076 if (hasDontEnumBug) {
1077 var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
1078 for (var j = 0; j < dontEnumsLength; j++) {
1079 var dontEnum = dontEnums[j];
1080 if (!(skipConstructor && dontEnum === 'constructor') && owns(object, dontEnum)) {
1081 pushCall(theKeys, dontEnum);
1089 var keysWorksWithArguments = $Object.keys && (function () {
1091 return $Object.keys(arguments).length === 2;
1093 var keysHasArgumentsLengthBug = $Object.keys && (function () {
1094 var argKeys = $Object.keys(arguments);
1095 return arguments.length !== 1 || argKeys.length !== 1 || argKeys[0] !== 1;
1097 var originalKeys = $Object.keys;
1098 defineProperties($Object, {
1099 keys: function keys(object) {
1100 if (isArguments(object)) {
1101 return originalKeys(arraySlice(object));
1103 return originalKeys(object);
1106 }, !keysWorksWithArguments || keysHasArgumentsLengthBug);
1113 var hasNegativeMonthYearBug = new Date(-3509827329600292).getUTCMonth() !== 0;
1114 var aNegativeTestDate = new Date(-1509842289600292);
1115 var aPositiveTestDate = new Date(1449662400000);
1116 var hasToUTCStringFormatBug = aNegativeTestDate.toUTCString() !== 'Mon, 01 Jan -45875 11:59:59 GMT';
1117 var hasToDateStringFormatBug;
1118 var hasToStringFormatBug;
1119 var timeZoneOffset = aNegativeTestDate.getTimezoneOffset();
1120 if (timeZoneOffset < -720) {
1121 hasToDateStringFormatBug = aNegativeTestDate.toDateString() !== 'Tue Jan 02 -45875';
1122 hasToStringFormatBug = !(/^Thu Dec 10 2015 \d\d:\d\d:\d\d GMT[-\+]\d\d\d\d(?: |$)/).test(aPositiveTestDate.toString());
1124 hasToDateStringFormatBug = aNegativeTestDate.toDateString() !== 'Mon Jan 01 -45875';
1125 hasToStringFormatBug = !(/^Wed Dec 09 2015 \d\d:\d\d:\d\d GMT[-\+]\d\d\d\d(?: |$)/).test(aPositiveTestDate.toString());
1128 var originalGetFullYear = call.bind(Date.prototype.getFullYear);
1129 var originalGetMonth = call.bind(Date.prototype.getMonth);
1130 var originalGetDate = call.bind(Date.prototype.getDate);
1131 var originalGetUTCFullYear = call.bind(Date.prototype.getUTCFullYear);
1132 var originalGetUTCMonth = call.bind(Date.prototype.getUTCMonth);
1133 var originalGetUTCDate = call.bind(Date.prototype.getUTCDate);
1134 var originalGetUTCDay = call.bind(Date.prototype.getUTCDay);
1135 var originalGetUTCHours = call.bind(Date.prototype.getUTCHours);
1136 var originalGetUTCMinutes = call.bind(Date.prototype.getUTCMinutes);
1137 var originalGetUTCSeconds = call.bind(Date.prototype.getUTCSeconds);
1138 var originalGetUTCMilliseconds = call.bind(Date.prototype.getUTCMilliseconds);
1139 var dayName = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
1140 var monthName = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
1141 var daysInMonth = function daysInMonth(month, year) {
1142 return originalGetDate(new Date(year, month, 0));
1145 defineProperties(Date.prototype, {
1146 getFullYear: function getFullYear() {
1147 if (!this || !(this instanceof Date)) {
1148 throw new TypeError('this is not a Date object.');
1150 var year = originalGetFullYear(this);
1151 if (year < 0 && originalGetMonth(this) > 11) {
1156 getMonth: function getMonth() {
1157 if (!this || !(this instanceof Date)) {
1158 throw new TypeError('this is not a Date object.');
1160 var year = originalGetFullYear(this);
1161 var month = originalGetMonth(this);
1162 if (year < 0 && month > 11) {
1167 getDate: function getDate() {
1168 if (!this || !(this instanceof Date)) {
1169 throw new TypeError('this is not a Date object.');
1171 var year = originalGetFullYear(this);
1172 var month = originalGetMonth(this);
1173 var date = originalGetDate(this);
1174 if (year < 0 && month > 11) {
1178 var days = daysInMonth(0, year + 1);
1179 return (days - date) + 1;
1183 getUTCFullYear: function getUTCFullYear() {
1184 if (!this || !(this instanceof Date)) {
1185 throw new TypeError('this is not a Date object.');
1187 var year = originalGetUTCFullYear(this);
1188 if (year < 0 && originalGetUTCMonth(this) > 11) {
1193 getUTCMonth: function getUTCMonth() {
1194 if (!this || !(this instanceof Date)) {
1195 throw new TypeError('this is not a Date object.');
1197 var year = originalGetUTCFullYear(this);
1198 var month = originalGetUTCMonth(this);
1199 if (year < 0 && month > 11) {
1204 getUTCDate: function getUTCDate() {
1205 if (!this || !(this instanceof Date)) {
1206 throw new TypeError('this is not a Date object.');
1208 var year = originalGetUTCFullYear(this);
1209 var month = originalGetUTCMonth(this);
1210 var date = originalGetUTCDate(this);
1211 if (year < 0 && month > 11) {
1215 var days = daysInMonth(0, year + 1);
1216 return (days - date) + 1;
1220 }, hasNegativeMonthYearBug);
1222 defineProperties(Date.prototype, {
1223 toUTCString: function toUTCString() {
1224 if (!this || !(this instanceof Date)) {
1225 throw new TypeError('this is not a Date object.');
1227 var day = originalGetUTCDay(this);
1228 var date = originalGetUTCDate(this);
1229 var month = originalGetUTCMonth(this);
1230 var year = originalGetUTCFullYear(this);
1231 var hour = originalGetUTCHours(this);
1232 var minute = originalGetUTCMinutes(this);
1233 var second = originalGetUTCSeconds(this);
1234 return dayName[day] + ', ' +
1235 (date < 10 ? '0' + date : date) + ' ' +
1236 monthName[month] + ' ' +
1238 (hour < 10 ? '0' + hour : hour) + ':' +
1239 (minute < 10 ? '0' + minute : minute) + ':' +
1240 (second < 10 ? '0' + second : second) + ' GMT';
1242 }, hasNegativeMonthYearBug || hasToUTCStringFormatBug);
1245 defineProperties(Date.prototype, {
1246 toDateString: function toDateString() {
1247 if (!this || !(this instanceof Date)) {
1248 throw new TypeError('this is not a Date object.');
1250 var day = this.getDay();
1251 var date = this.getDate();
1252 var month = this.getMonth();
1253 var year = this.getFullYear();
1254 return dayName[day] + ' ' +
1255 monthName[month] + ' ' +
1256 (date < 10 ? '0' + date : date) + ' ' +
1259 }, hasNegativeMonthYearBug || hasToDateStringFormatBug);
1261 // can't use defineProperties here because of toString enumeration issue in IE <= 8
1262 if (hasNegativeMonthYearBug || hasToStringFormatBug) {
1263 Date.prototype.toString = function toString() {
1264 if (!this || !(this instanceof Date)) {
1265 throw new TypeError('this is not a Date object.');
1267 var day = this.getDay();
1268 var date = this.getDate();
1269 var month = this.getMonth();
1270 var year = this.getFullYear();
1271 var hour = this.getHours();
1272 var minute = this.getMinutes();
1273 var second = this.getSeconds();
1274 var timezoneOffset = this.getTimezoneOffset();
1275 var hoursOffset = Math.floor(Math.abs(timezoneOffset) / 60);
1276 var minutesOffset = Math.floor(Math.abs(timezoneOffset) % 60);
1277 return dayName[day] + ' ' +
1278 monthName[month] + ' ' +
1279 (date < 10 ? '0' + date : date) + ' ' +
1281 (hour < 10 ? '0' + hour : hour) + ':' +
1282 (minute < 10 ? '0' + minute : minute) + ':' +
1283 (second < 10 ? '0' + second : second) + ' GMT' +
1284 (timezoneOffset > 0 ? '-' : '+') +
1285 (hoursOffset < 10 ? '0' + hoursOffset : hoursOffset) +
1286 (minutesOffset < 10 ? '0' + minutesOffset : minutesOffset);
1288 if (supportsDescriptors) {
1289 $Object.defineProperty(Date.prototype, 'toString', {
1298 // http://es5.github.com/#x15.9.5.43
1299 // This function returns a String value represent the instance in time
1300 // represented by this Date object. The format of the String is the Date Time
1301 // string format defined in 15.9.1.15. All fields are present in the String.
1302 // The time zone is always UTC, denoted by the suffix Z. If the time value of
1303 // this object is not a finite Number a RangeError exception is thrown.
1304 var negativeDate = -62198755200000;
1305 var negativeYearString = '-000001';
1306 var hasNegativeDateBug = Date.prototype.toISOString && new Date(negativeDate).toISOString().indexOf(negativeYearString) === -1;
1307 var hasSafari51DateBug = Date.prototype.toISOString && new Date(-1).toISOString() !== '1969-12-31T23:59:59.999Z';
1309 var getTime = call.bind(Date.prototype.getTime);
1311 defineProperties(Date.prototype, {
1312 toISOString: function toISOString() {
1313 if (!isFinite(this) || !isFinite(getTime(this))) {
1314 // Adope Photoshop requires the second check.
1315 throw new RangeError('Date.prototype.toISOString called on non-finite value.');
1318 var year = originalGetUTCFullYear(this);
1320 var month = originalGetUTCMonth(this);
1321 // see https://github.com/es-shims/es5-shim/issues/111
1322 year += Math.floor(month / 12);
1323 month = (month % 12 + 12) % 12;
1325 // the date time string format is specified in 15.9.1.15.
1326 var result = [month + 1, originalGetUTCDate(this), originalGetUTCHours(this), originalGetUTCMinutes(this), originalGetUTCSeconds(this)];
1328 (year < 0 ? '-' : (year > 9999 ? '+' : '')) +
1329 strSlice('00000' + Math.abs(year), (0 <= year && year <= 9999) ? -4 : -6)
1332 for (var i = 0; i < result.length; ++i) {
1333 // pad months, days, hours, minutes, and seconds to have two digits.
1334 result[i] = strSlice('00' + result[i], -2);
1336 // pad milliseconds to have three digits.
1338 year + '-' + arraySlice(result, 0, 2).join('-') +
1339 'T' + arraySlice(result, 2).join(':') + '.' +
1340 strSlice('000' + originalGetUTCMilliseconds(this), -3) + 'Z'
1343 }, hasNegativeDateBug || hasSafari51DateBug);
1346 // http://es5.github.com/#x15.9.5.44
1347 // This function provides a String representation of a Date object for use by
1348 // JSON.stringify (15.12.3).
1349 var dateToJSONIsSupported = (function () {
1351 return Date.prototype.toJSON &&
1352 new Date(NaN).toJSON() === null &&
1353 new Date(negativeDate).toJSON().indexOf(negativeYearString) !== -1 &&
1354 Date.prototype.toJSON.call({ // generic
1355 toISOString: function () { return true; }
1361 if (!dateToJSONIsSupported) {
1362 Date.prototype.toJSON = function toJSON(key) {
1363 // When the toJSON method is called with argument key, the following
1366 // 1. Let O be the result of calling ToObject, giving it the this
1367 // value as its argument.
1368 // 2. Let tv be ES.ToPrimitive(O, hint Number).
1369 var O = $Object(this);
1370 var tv = ES.ToPrimitive(O);
1371 // 3. If tv is a Number and is not finite, return null.
1372 if (typeof tv === 'number' && !isFinite(tv)) {
1375 // 4. Let toISO be the result of calling the [[Get]] internal method of
1376 // O with argument "toISOString".
1377 var toISO = O.toISOString;
1378 // 5. If IsCallable(toISO) is false, throw a TypeError exception.
1379 if (!isCallable(toISO)) {
1380 throw new TypeError('toISOString property is not callable');
1382 // 6. Return the result of calling the [[Call]] internal method of
1383 // toISO with O as the this value and an empty argument list.
1384 return toISO.call(O);
1386 // NOTE 1 The argument is ignored.
1388 // NOTE 2 The toJSON function is intentionally generic; it does not
1389 // require that its this value be a Date object. Therefore, it can be
1390 // transferred to other kinds of objects for use as a method. However,
1391 // it does require that any such object have a toISOString method. An
1392 // object is free to use the argument key to filter its
1398 // http://es5.github.com/#x15.9.4.2
1399 // based on work shared by Daniel Friesen (dantman)
1400 // http://gist.github.com/303249
1401 var supportsExtendedYears = Date.parse('+033658-09-27T01:46:40.000Z') === 1e15;
1402 var acceptsInvalidDates = !isNaN(Date.parse('2012-04-04T24:00:00.500Z')) || !isNaN(Date.parse('2012-11-31T23:59:59.000Z')) || !isNaN(Date.parse('2012-12-31T23:59:60.000Z'));
1403 var doesNotParseY2KNewYear = isNaN(Date.parse('2000-01-01T00:00:00.000Z'));
1404 if (doesNotParseY2KNewYear || acceptsInvalidDates || !supportsExtendedYears) {
1405 // XXX global assignment won't work in embeddings that use
1406 // an alternate object for the context.
1407 /* global Date: true */
1408 /* eslint-disable no-undef */
1409 var maxSafeUnsigned32Bit = Math.pow(2, 31) - 1;
1410 var hasSafariSignedIntBug = isActualNaN(new Date(1970, 0, 1, 0, 0, 0, maxSafeUnsigned32Bit + 1).getTime());
1411 /* eslint-disable no-implicit-globals */
1412 Date = (function (NativeDate) {
1413 /* eslint-enable no-implicit-globals */
1414 /* eslint-enable no-undef */
1415 // Date.length === 7
1416 var DateShim = function Date(Y, M, D, h, m, s, ms) {
1417 var length = arguments.length;
1419 if (this instanceof NativeDate) {
1422 if (hasSafariSignedIntBug && length >= 7 && ms > maxSafeUnsigned32Bit) {
1423 // work around a Safari 8/9 bug where it treats the seconds as signed
1424 var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
1425 var sToShift = Math.floor(msToShift / 1e3);
1426 seconds += sToShift;
1427 millis -= sToShift * 1e3;
1429 date = length === 1 && $String(Y) === Y ? // isString(Y)
1430 // We explicitly pass it through parse:
1431 new NativeDate(DateShim.parse(Y)) :
1432 // We have to manually make calls depending on argument
1434 length >= 7 ? new NativeDate(Y, M, D, h, m, seconds, millis) :
1435 length >= 6 ? new NativeDate(Y, M, D, h, m, seconds) :
1436 length >= 5 ? new NativeDate(Y, M, D, h, m) :
1437 length >= 4 ? new NativeDate(Y, M, D, h) :
1438 length >= 3 ? new NativeDate(Y, M, D) :
1439 length >= 2 ? new NativeDate(Y, M) :
1440 length >= 1 ? new NativeDate(Y instanceof NativeDate ? +Y : Y) :
1443 date = NativeDate.apply(this, arguments);
1445 if (!isPrimitive(date)) {
1446 // Prevent mixups with unfixed Date object
1447 defineProperties(date, { constructor: DateShim }, true);
1452 // 15.9.1.15 Date Time String Format.
1453 var isoDateExpression = new RegExp('^' +
1454 '(\\d{4}|[+-]\\d{6})' + // four-digit year capture or sign +
1455 // 6-digit extended year
1456 '(?:-(\\d{2})' + // optional month capture
1457 '(?:-(\\d{2})' + // optional day capture
1458 '(?:' + // capture hours:minutes:seconds.milliseconds
1459 'T(\\d{2})' + // hours capture
1460 ':(\\d{2})' + // minutes capture
1461 '(?:' + // optional :seconds.milliseconds
1462 ':(\\d{2})' + // seconds capture
1463 '(?:(\\.\\d{1,}))?' + // milliseconds capture
1465 '(' + // capture UTC offset component
1466 'Z|' + // UTC capture
1467 '(?:' + // offset specifier +/-hours:minutes
1468 '([-+])' + // sign capture
1469 '(\\d{2})' + // hours offset capture
1470 ':(\\d{2})' + // minutes offset capture
1475 var months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365];
1477 var dayFromMonth = function dayFromMonth(year, month) {
1478 var t = month > 1 ? 1 : 0;
1481 Math.floor((year - 1969 + t) / 4) -
1482 Math.floor((year - 1901 + t) / 100) +
1483 Math.floor((year - 1601 + t) / 400) +
1488 var toUTC = function toUTC(t) {
1491 if (hasSafariSignedIntBug && ms > maxSafeUnsigned32Bit) {
1492 // work around a Safari 8/9 bug where it treats the seconds as signed
1493 var msToShift = Math.floor(ms / maxSafeUnsigned32Bit) * maxSafeUnsigned32Bit;
1494 var sToShift = Math.floor(msToShift / 1e3);
1496 ms -= sToShift * 1e3;
1498 return $Number(new NativeDate(1970, 0, 1, 0, 0, s, ms));
1501 // Copy any custom methods a 3rd party library may have added
1502 for (var key in NativeDate) {
1503 if (owns(NativeDate, key)) {
1504 DateShim[key] = NativeDate[key];
1508 // Copy "native" methods explicitly; they may be non-enumerable
1509 defineProperties(DateShim, {
1510 now: NativeDate.now,
1513 DateShim.prototype = NativeDate.prototype;
1514 defineProperties(DateShim.prototype, {
1515 constructor: DateShim
1518 // Upgrade Date.parse to handle simplified ISO 8601 strings
1519 var parseShim = function parse(string) {
1520 var match = isoDateExpression.exec(string);
1522 // parse months, days, hours, minutes, seconds, and milliseconds
1523 // provide default values if necessary
1524 // parse the UTC offset component
1525 var year = $Number(match[1]),
1526 month = $Number(match[2] || 1) - 1,
1527 day = $Number(match[3] || 1) - 1,
1528 hour = $Number(match[4] || 0),
1529 minute = $Number(match[5] || 0),
1530 second = $Number(match[6] || 0),
1531 millisecond = Math.floor($Number(match[7] || 0) * 1000),
1532 // When time zone is missed, local offset should be used
1534 // see https://bugs.ecmascript.org/show_bug.cgi?id=112
1535 isLocalTime = Boolean(match[4] && !match[8]),
1536 signOffset = match[9] === '-' ? 1 : -1,
1537 hourOffset = $Number(match[10] || 0),
1538 minuteOffset = $Number(match[11] || 0),
1540 var hasMinutesOrSecondsOrMilliseconds = minute > 0 || second > 0 || millisecond > 0;
1542 hour < (hasMinutesOrSecondsOrMilliseconds ? 24 : 25) &&
1543 minute < 60 && second < 60 && millisecond < 1000 &&
1544 month > -1 && month < 12 && hourOffset < 24 &&
1545 minuteOffset < 60 && // detect invalid offsets
1547 day < (dayFromMonth(year, month + 1) - dayFromMonth(year, month))
1550 (dayFromMonth(year, month) + day) * 24 +
1552 hourOffset * signOffset
1555 (result + minute + minuteOffset * signOffset) * 60 +
1557 ) * 1000 + millisecond;
1559 result = toUTC(result);
1561 if (-8.64e15 <= result && result <= 8.64e15) {
1567 return NativeDate.parse.apply(this, arguments);
1569 defineProperties(DateShim, { parse: parseShim });
1573 /* global Date: false */
1577 // http://es5.github.com/#x15.9.4.4
1579 Date.now = function now() {
1580 return new Date().getTime();
1590 // http://es5.github.com/#x15.7.4.5
1591 var hasToFixedBugs = NumberPrototype.toFixed && (
1592 (0.00008).toFixed(3) !== '0.000' ||
1593 (0.9).toFixed(0) !== '1' ||
1594 (1.255).toFixed(2) !== '1.25' ||
1595 (1000000000000000128).toFixed(0) !== '1000000000000000128'
1598 var toFixedHelpers = {
1601 data: [0, 0, 0, 0, 0, 0],
1602 multiply: function multiply(n, c) {
1605 while (++i < toFixedHelpers.size) {
1606 c2 += n * toFixedHelpers.data[i];
1607 toFixedHelpers.data[i] = c2 % toFixedHelpers.base;
1608 c2 = Math.floor(c2 / toFixedHelpers.base);
1611 divide: function divide(n) {
1612 var i = toFixedHelpers.size;
1615 c += toFixedHelpers.data[i];
1616 toFixedHelpers.data[i] = Math.floor(c / n);
1617 c = (c % n) * toFixedHelpers.base;
1620 numToString: function numToString() {
1621 var i = toFixedHelpers.size;
1624 if (s !== '' || i === 0 || toFixedHelpers.data[i] !== 0) {
1625 var t = $String(toFixedHelpers.data[i]);
1629 s += strSlice('0000000', 0, 7 - t.length) + t;
1635 pow: function pow(x, n, acc) {
1636 return (n === 0 ? acc : (n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc)));
1638 log: function log(x) {
1641 while (x2 >= 4096) {
1653 var toFixedShim = function toFixed(fractionDigits) {
1654 var f, x, s, m, e, z, j, k;
1656 // Test for NaN and round fractionDigits down
1657 f = $Number(fractionDigits);
1658 f = isActualNaN(f) ? 0 : Math.floor(f);
1660 if (f < 0 || f > 20) {
1661 throw new RangeError('Number.toFixed called with invalid number of decimals');
1666 if (isActualNaN(x)) {
1670 // If it is too big or small, return the string value of the number
1671 if (x <= -1e21 || x >= 1e21) {
1686 // -70 < log2(x) < 70
1687 e = toFixedHelpers.log(x * toFixedHelpers.pow(2, 69, 1)) - 69;
1688 z = (e < 0 ? x * toFixedHelpers.pow(2, -e, 1) : x / toFixedHelpers.pow(2, e, 1));
1689 z *= 0x10000000000000; // Math.pow(2, 52);
1695 toFixedHelpers.multiply(0, z);
1699 toFixedHelpers.multiply(1e7, 0);
1703 toFixedHelpers.multiply(toFixedHelpers.pow(10, j, 1), 0);
1707 toFixedHelpers.divide(1 << 23);
1711 toFixedHelpers.divide(1 << j);
1712 toFixedHelpers.multiply(1, 1);
1713 toFixedHelpers.divide(2);
1714 m = toFixedHelpers.numToString();
1716 toFixedHelpers.multiply(0, z);
1717 toFixedHelpers.multiply(1 << (-e), 0);
1718 m = toFixedHelpers.numToString() + strSlice('0.00000000000000000000', 2, 2 + f);
1726 m = s + strSlice('0.0000000000000000000', 0, f - k + 2) + m;
1728 m = s + strSlice(m, 0, k - f) + '.' + strSlice(m, k - f);
1736 defineProperties(NumberPrototype, { toFixed: toFixedShim }, hasToFixedBugs);
1738 var hasToPrecisionUndefinedBug = (function () {
1740 return 1.0.toPrecision(undefined) === '1';
1745 var originalToPrecision = NumberPrototype.toPrecision;
1746 defineProperties(NumberPrototype, {
1747 toPrecision: function toPrecision(precision) {
1748 return typeof precision === 'undefined' ? originalToPrecision.call(this) : originalToPrecision.call(this, precision);
1750 }, hasToPrecisionUndefinedBug);
1758 // http://es5.github.com/#x15.5.4.14
1760 // [bugfix, IE lt 9, firefox 4, Konqueror, Opera, obscure browsers]
1761 // Many browsers do not split properly with regular expressions or they
1762 // do not perform the split correctly under obscure conditions.
1763 // See http://blog.stevenlevithan.com/archives/cross-browser-split
1764 // I've tested in many browsers and this seems to cover the deviant ones:
1765 // 'ab'.split(/(?:ab)*/) should be ["", ""], not [""]
1766 // '.'.split(/(.?)(.?)/) should be ["", ".", "", ""], not ["", ""]
1767 // 'tesst'.split(/(s)*/) should be ["t", undefined, "e", "s", "t"], not
1768 // [undefined, "t", undefined, "e", ...]
1769 // ''.split(/.?/) should be [], not [""]
1770 // '.'.split(/()()/) should be ["."], not ["", "", "."]
1773 'ab'.split(/(?:ab)*/).length !== 2 ||
1774 '.'.split(/(.?)(.?)/).length !== 4 ||
1775 'tesst'.split(/(s)*/)[1] === 't' ||
1776 'test'.split(/(?:)/, -1).length !== 4 ||
1777 ''.split(/.?/).length ||
1778 '.'.split(/()()/).length > 1
1781 var compliantExecNpcg = typeof (/()??/).exec('')[1] === 'undefined'; // NPCG: nonparticipating capturing group
1782 var maxSafe32BitInt = Math.pow(2, 32) - 1;
1784 StringPrototype.split = function (separator, limit) {
1785 var string = String(this);
1786 if (typeof separator === 'undefined' && limit === 0) {
1790 // If `separator` is not a regex, use native split
1791 if (!isRegex(separator)) {
1792 return strSplit(this, separator, limit);
1796 var flags = (separator.ignoreCase ? 'i' : '') +
1797 (separator.multiline ? 'm' : '') +
1798 (separator.unicode ? 'u' : '') + // in ES6
1799 (separator.sticky ? 'y' : ''), // Firefox 3+ and ES6
1801 // Make `global` and avoid `lastIndex` issues by working with a copy
1802 separator2, match, lastIndex, lastLength;
1803 var separatorCopy = new RegExp(separator.source, flags + 'g');
1804 if (!compliantExecNpcg) {
1805 // Doesn't need flags gy, but they don't hurt
1806 separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
1808 /* Values for `limit`, per the spec:
1809 * If undefined: 4294967295 // maxSafe32BitInt
1810 * If 0, Infinity, or NaN: 0
1811 * If positive number: limit = Math.floor(limit); if (limit > 4294967295) limit -= 4294967296;
1812 * If negative number: 4294967296 - Math.floor(Math.abs(limit))
1813 * If other: Type-convert, then use the above rules
1815 var splitLimit = typeof limit === 'undefined' ? maxSafe32BitInt : ES.ToUint32(limit);
1816 match = separatorCopy.exec(string);
1818 // `separatorCopy.lastIndex` is not reliable cross-browser
1819 lastIndex = match.index + match[0].length;
1820 if (lastIndex > lastLastIndex) {
1821 pushCall(output, strSlice(string, lastLastIndex, match.index));
1822 // Fix browsers whose `exec` methods don't consistently return `undefined` for
1823 // nonparticipating capturing groups
1824 if (!compliantExecNpcg && match.length > 1) {
1825 /* eslint-disable no-loop-func */
1826 match[0].replace(separator2, function () {
1827 for (var i = 1; i < arguments.length - 2; i++) {
1828 if (typeof arguments[i] === 'undefined') {
1833 /* eslint-enable no-loop-func */
1835 if (match.length > 1 && match.index < string.length) {
1836 array_push.apply(output, arraySlice(match, 1));
1838 lastLength = match[0].length;
1839 lastLastIndex = lastIndex;
1840 if (output.length >= splitLimit) {
1844 if (separatorCopy.lastIndex === match.index) {
1845 separatorCopy.lastIndex++; // Avoid an infinite loop
1847 match = separatorCopy.exec(string);
1849 if (lastLastIndex === string.length) {
1850 if (lastLength || !separatorCopy.test('')) {
1851 pushCall(output, '');
1854 pushCall(output, strSlice(string, lastLastIndex));
1856 return output.length > splitLimit ? arraySlice(output, 0, splitLimit) : output;
1861 // If separator is undefined, then the result array contains just one String,
1862 // which is the this value (converted to a String). If limit is not undefined,
1863 // then the output array is truncated so that it contains no more than limit
1865 // "0".split(undefined, 0) -> []
1866 } else if ('0'.split(void 0, 0).length) {
1867 StringPrototype.split = function split(separator, limit) {
1868 if (typeof separator === 'undefined' && limit === 0) {
1871 return strSplit(this, separator, limit);
1875 var str_replace = StringPrototype.replace;
1876 var replaceReportsGroupsCorrectly = (function () {
1878 'x'.replace(/x(.)?/g, function (match, group) {
1879 pushCall(groups, group);
1881 return groups.length === 1 && typeof groups[0] === 'undefined';
1884 if (!replaceReportsGroupsCorrectly) {
1885 StringPrototype.replace = function replace(searchValue, replaceValue) {
1886 var isFn = isCallable(replaceValue);
1887 var hasCapturingGroups = isRegex(searchValue) && (/\)[*?]/).test(searchValue.source);
1888 if (!isFn || !hasCapturingGroups) {
1889 return str_replace.call(this, searchValue, replaceValue);
1891 var wrappedReplaceValue = function (match) {
1892 var length = arguments.length;
1893 var originalLastIndex = searchValue.lastIndex;
1894 searchValue.lastIndex = 0;
1895 var args = searchValue.exec(match) || [];
1896 searchValue.lastIndex = originalLastIndex;
1897 pushCall(args, arguments[length - 2], arguments[length - 1]);
1898 return replaceValue.apply(this, args);
1900 return str_replace.call(this, searchValue, wrappedReplaceValue);
1905 // ECMA-262, 3rd B.2.3
1906 // Not an ECMAScript standard, although ECMAScript 3rd Edition has a
1907 // non-normative section suggesting uniform semantics and it should be
1908 // normalized across all browsers
1909 // [bugfix, IE lt 9] IE < 9 substr() with negative value not working in IE
1910 var string_substr = StringPrototype.substr;
1911 var hasNegativeSubstrBug = ''.substr && '0b'.substr(-1) !== 'b';
1912 defineProperties(StringPrototype, {
1913 substr: function substr(start, length) {
1914 var normalizedStart = start;
1916 normalizedStart = max(this.length + start, 0);
1918 return string_substr.call(this, normalizedStart, length);
1920 }, hasNegativeSubstrBug);
1923 // whitespace from: http://es5.github.io/#x15.5.4.20
1924 var ws = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
1925 '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028' +
1927 var zeroWidth = '\u200b';
1928 var wsRegexChars = '[' + ws + ']';
1929 var trimBeginRegexp = new RegExp('^' + wsRegexChars + wsRegexChars + '*');
1930 var trimEndRegexp = new RegExp(wsRegexChars + wsRegexChars + '*$');
1931 var hasTrimWhitespaceBug = StringPrototype.trim && (ws.trim() || !zeroWidth.trim());
1932 defineProperties(StringPrototype, {
1933 // http://blog.stevenlevithan.com/archives/faster-trim-javascript
1934 // http://perfectionkills.com/whitespace-deviations/
1935 trim: function trim() {
1936 if (typeof this === 'undefined' || this === null) {
1937 throw new TypeError("can't convert " + this + ' to object');
1939 return $String(this).replace(trimBeginRegexp, '').replace(trimEndRegexp, '');
1941 }, hasTrimWhitespaceBug);
1942 var trim = call.bind(String.prototype.trim);
1944 var hasLastIndexBug = StringPrototype.lastIndexOf && 'abcあい'.lastIndexOf('あい', 2) !== -1;
1945 defineProperties(StringPrototype, {
1946 lastIndexOf: function lastIndexOf(searchString) {
1947 if (typeof this === 'undefined' || this === null) {
1948 throw new TypeError("can't convert " + this + ' to object');
1950 var S = $String(this);
1951 var searchStr = $String(searchString);
1952 var numPos = arguments.length > 1 ? $Number(arguments[1]) : NaN;
1953 var pos = isActualNaN(numPos) ? Infinity : ES.ToInteger(numPos);
1954 var start = min(max(pos, 0), S.length);
1955 var searchLen = searchStr.length;
1956 var k = start + searchLen;
1958 k = max(0, k - searchLen);
1959 var index = strIndexOf(strSlice(S, k, start + searchLen), searchStr);
1966 }, hasLastIndexBug);
1968 var originalLastIndexOf = StringPrototype.lastIndexOf;
1969 defineProperties(StringPrototype, {
1970 lastIndexOf: function lastIndexOf(searchString) {
1971 return originalLastIndexOf.apply(this, arguments);
1973 }, StringPrototype.lastIndexOf.length !== 1);
1976 /* eslint-disable radix */
1977 if (parseInt(ws + '08') !== 8 || parseInt(ws + '0x16') !== 22) {
1978 /* eslint-enable radix */
1979 /* global parseInt: true */
1980 parseInt = (function (origParseInt) {
1981 var hexRegex = /^[\-+]?0[xX]/;
1982 return function parseInt(str, radix) {
1983 var string = trim(String(str));
1984 var defaultedRadix = $Number(radix) || (hexRegex.test(string) ? 16 : 10);
1985 return origParseInt(string, defaultedRadix);
1990 // https://es5.github.io/#x15.1.2.3
1991 if (1 / parseFloat('-0') !== -Infinity) {
1992 /* global parseFloat: true */
1993 parseFloat = (function (origParseFloat) {
1994 return function parseFloat(string) {
1995 var inputString = trim(String(string));
1996 var result = origParseFloat(inputString);
1997 return result === 0 && strSlice(inputString, 0, 1) === '-' ? -0 : result;
2002 if (String(new RangeError('test')) !== 'RangeError: test') {
2003 var errorToStringShim = function toString() {
2004 if (typeof this === 'undefined' || this === null) {
2005 throw new TypeError("can't convert " + this + ' to object');
2007 var name = this.name;
2008 if (typeof name === 'undefined') {
2010 } else if (typeof name !== 'string') {
2011 name = $String(name);
2013 var msg = this.message;
2014 if (typeof msg === 'undefined') {
2016 } else if (typeof msg !== 'string') {
2025 return name + ': ' + msg;
2027 // can't use defineProperties here because of toString enumeration issue in IE <= 8
2028 Error.prototype.toString = errorToStringShim;
2031 if (supportsDescriptors) {
2032 var ensureNonEnumerable = function (obj, prop) {
2033 if (isEnum(obj, prop)) {
2034 var desc = Object.getOwnPropertyDescriptor(obj, prop);
2035 if (desc.configurable) {
2036 desc.enumerable = false;
2037 Object.defineProperty(obj, prop, desc);
2041 ensureNonEnumerable(Error.prototype, 'message');
2042 if (Error.prototype.message !== '') {
2043 Error.prototype.message = '';
2045 ensureNonEnumerable(Error.prototype, 'name');
2048 if (String(/a/mig) !== '/a/gim') {
2049 var regexToString = function toString() {
2050 var str = '/' + this.source + '/';
2054 if (this.ignoreCase) {
2057 if (this.multiline) {
2062 // can't use defineProperties here because of toString enumeration issue in IE <= 8
2063 RegExp.prototype.toString = regexToString;