Skip to content

Instantly share code, notes, and snippets.

@esson
Created August 23, 2013 10:21
Show Gist options
  • Save esson/6317769 to your computer and use it in GitHub Desktop.
Save esson/6317769 to your computer and use it in GitHub Desktop.
// Array Polyfills
// ---------------
(function () {
if (!Array.prototype.indexOf) {
// Production steps of ECMA-262, Edition 5, 15.4.4.14
// Reference: http://es5.github.com/#x15.4.4.14
Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
"use strict";
if (this == null) {
throw new TypeError();
}
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n) { // shortcut for verifying if it's NaN
n = 0;
} else if (n != 0 && n != Infinity && n != -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
if (!Array.prototype.lastIndexOf) {
// Production steps of ECMA-262, Edition 5, 15.4.4.15
// Reference: http://es5.github.com/#x15.4.4.15
Array.prototype.lastIndexOf = function (searchElement /*, fromIndex*/) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (len === 0)
return -1;
var n = len;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n != n)
n = 0;
else if (n != 0 && n != (1 / 0) && n != -(1 / 0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
var k = n >= 0
? Math.min(n, len - 1)
: len - Math.abs(n);
for (; k >= 0; k--) {
if (k in t && t[k] === searchElement)
return k;
}
return -1;
};
}
if (!Array.prototype.every) {
// Production steps of ECMA-262, Edition 5, 15.4.4.16
// Reference: http://es5.github.com/#x15.4.4.16
Array.prototype.every = function (callbackfn /*, thisArg */) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof callbackfn != "function")
throw new TypeError();
var thisArg = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t && !callbackfn.call(thisArg, t[i], i, t))
return false;
}
return true;
};
}
if (!Array.prototype.some) {
// Production steps of ECMA-262, Edition 5, 15.4.4.17
// Reference: http://es5.github.com/#x15.4.4.17
Array.prototype.some = function (callbackfn /*, thisArg */) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof callbackfn != "function")
throw new TypeError();
var thisArg = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t && callbackfn.call(thisArg, t[i], i, t))
return true;
}
return false;
};
}
if (!Array.prototype.forEach) {
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
Array.prototype.forEach = function forEach(callbackfn, thisArg) {
var T, k;
if (this == null) {
throw new TypeError("this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0; // Hack to convert O.length to a UInt32
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if ({}.toString.call(callbackfn) !== "[object Function]") {
throw new TypeError(callbackfn + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (thisArg) {
T = thisArg;
}
// 6. Let k be 0
k = 0;
// 7. Repeat, while k < len
while (k < len) {
var kValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (Object.prototype.hasOwnProperty.call(O, k)) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Call the Call internal method of callback with T as the this value and
// argument list containing kValue, k, and O.
callbackfn.call(T, kValue, k, O);
}
// d. Increase k by 1.
k++;
}
// 8. return undefined
};
}
if (!Array.prototype.map) {
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
Array.prototype.map = function (callbackfn, thisArg) {
var T, A, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
var O = Object(this);
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
// 3. Let len be ToUint32(lenValue).
var len = O.length >>> 0;
// 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
// See: http://es5.github.com/#x9.11
if (typeof callbackfn !== "function") {
throw new TypeError(callbackfn + " is not a function");
}
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (thisArg) {
T = thisArg;
}
// 6. Let A be a new array created as if by the expression new Array(len) where Array is
// the standard built-in constructor with that name and len is the value of len.
A = new Array(len);
// 7. Let k be 0
k = 0;
// 8. Repeat, while k < len
while (k < len) {
var kValue, mappedValue;
// a. Let Pk be ToString(k).
// This is implicit for LHS operands of the in operator
// b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
// This step can be combined with c
// c. If kPresent is true, then
if (k in O) {
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
kValue = O[k];
// ii. Let mappedValue be the result of calling the Call internal method of callback
// with T as the this value and argument list containing kValue, k, and O.
mappedValue = callbackfn.call(T, kValue, k, O);
// iii. Call the DefineOwnProperty internal method of A with arguments
// Pk, Property Descriptor {Value: mappedValue, : true, Enumerable: true, Configurable: true},
// and false.
// In browsers that support Object.defineProperty, use the following:
// Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });
// For best browser support, use the following:
A[k] = mappedValue;
}
// d. Increase k by 1.
k++;
}
// 9. return A
return A;
};
}
if (!Array.prototype.filter) {
// Production steps of ECMA-262, Edition 5, 15.4.4.20
// Reference: http://es5.github.com/#x15.4.4.20
Array.prototype.filter = function (callbackfn /*, thisp */) {
"use strict";
if (this == null)
throw new TypeError();
var t = Object(this);
var len = t.length >>> 0;
if (typeof callbackfn != "function")
throw new TypeError();
var res = [];
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in t) {
var val = t[i]; // in case fun mutates this
if (callbackfn.call(thisp, val, i, t))
res.push(val);
}
}
return res;
};
}
if (!Array.prototype.reduce) {
// Production steps of ECMA-262, Edition 5, 15.4.4.21
// Reference: http://es5.github.com/#x15.4.4.21
Array.prototype.reduce = function (callbackfn, initialValue) {
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callbackfn) {
throw new TypeError(callbackfn + ' is not a function');
}
var index = 0, length = this.length >>> 0, value, isValueSet = false;
if (1 < arguments.length) {
value = initialValue;
isValueSet = true;
}
for (; length > index; ++index) {
if (!this.hasOwnProperty(index)) continue;
if (isValueSet) {
value = callbackfn(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
if (!Array.prototype.reduceRight) {
// Production steps of ECMA-262, Edition 5, 15.4.4.22
// Reference: http://es5.github.com/#x15.4.4.22
Array.prototype.reduceRight = function (callbackfn, initialValue) {
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduceRight. For instance,
// IE8 does not support strict mode, so this check is actually useless.
throw new TypeError('Array.prototype.reduceRight called on null or undefined');
}
if ('function' !== typeof callbackfn) {
throw new TypeError(callbackfn + ' is not a function');
}
var length = this.length >>> 0, index = length - 1, value, isValueSet = false;
if (1 < arguments.length) {
value = initialValue;
isValueSet = true;
}
for (; -1 < index; --index) {
if (!this.hasOwnProperty(index)) continue;
if (isValueSet) {
value = callbackfn(value, this[index], index, this);
} else {
value = this[index];
isValueSet = true;
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
})();
// String Polyfills
// ----------------
(function () {
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
if (!String.format) {
String.format = function () {
var
formatString = arguments[0],
args = [],
result = '',
regex = /{(\d+)}$/g;
if (arguments[1] instanceof Array) {
args = arguments[1];
} else {
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
}
for (var i = 0; i < formatString.length; i++) {
result += formatString[i];
if (result.match(regex)) {
result = result.replace(regex, function (match, number) {
var index = parseInt(number, 10);
var arg = args[index];
if (typeof arg === 'undefined') {
throw new Error('The index of a format item is less than zero, or greater than or equal to the number of arguments in the arguments list.');
}
return arg;
});
}
}
return result;
};
}
})();
// Window Polyfills
// ----------------
(function () {
// Credit to Erik Möller
// URL: http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
var
lastTime = 0,
vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment