Skip to content

Instantly share code, notes, and snippets.

@bkardell
Last active November 10, 2015 11:18
Show Gist options
  • Save bkardell/c3d6e3c49a5853b38f83 to your computer and use it in GitHub Desktop.
Save bkardell/c3d6e3c49a5853b38f83 to your computer and use it in GitHub Desktop.
/**
* Shim for "fixing" IE's lack of support (IE < 9) for applying slice
* on host objects like NamedNodeMap, NodeList, and HTMLCollection
* (technically, since host objects have been implementation-dependent,
* at least before ES6, IE hasn't needed to work this way).
* Also works on strings, fixes IE < 9 to allow an explicit undefined
* for the 2nd argument (as in Firefox), and prevents errors when
* called on other DOM objects.
*/
(function () {
'use strict';
var _slice = Array.prototype.slice;
try {
// Can't be used with DOM elements in IE < 9
_slice.call(document.documentElement);
} catch (e) { // Fails in IE < 9
// This will work for genuine arrays, array-like objects,
// NamedNodeMap (attributes, entities, notations),
// NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
// and will not fail on other DOM objects (as do DOM elements in IE < 9)
var clone = function (arraylike, isStr, begin, end) {
var i, cloned = [],
size, len = arraylike.length;
var start = begin || 0;
start = (start >= 0) ? start: len + start;
var upTo = (end) ? end : len;
if (end < 0) {
upTo = len + end;
}
size = upTo - start;
if (size > 0) {
cloned = new Array(size);
if (isStr) {
for (i = 0; i < cloned.length; i++) {
cloned[i] = arraylike.charAt(start + i);
}
} else {
for (i = 0; i < cloned.length; i++) {
cloned[i] = arraylike[start + i];
}
}
}
return cloned;
};
Array.prototype.slice = function (begin, end) {
return (Object.prototype.toString.call(this) === '[object Array]') ?
_slice.call(this, begin, end || this.length) :
clone(this, this.charAt, begin, end);
};
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment