Created
February 8, 2018 19:59
-
-
Save Skateside/a64202dc1911a252968f09838f8200b5 to your computer and use it in GitHub Desktop.
A simple polyfill for the "jQuery style methods" that have been added recently. Written in ES6 syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function polyfill(object, name, value) { | |
if (typeof object[name] !== typeof value) { | |
Object.defineProperty(object, name, { | |
value, | |
configurable: true, | |
enumerable: false, | |
writable: true | |
}); | |
} | |
} | |
function polfillAll(objects, methods) { | |
if (!Array.isArray(objects)) { | |
objects = [objects]; | |
} | |
objects.forEach((object) => { | |
Object | |
.entries(methods) | |
.forEach(([key, value]) => polyfill(object, key, value)); | |
}); | |
} | |
polyfill( | |
Object, | |
"entries", | |
(object) => Object.keys(object).map((key) => [key, object[key]]) | |
); | |
let addToFrag = (...args) => { | |
let frag = document.createDocumentFragment(); | |
args.forEach((arg) => { | |
frag.appendChild( | |
arg instanceof Node | |
? arg | |
: document.createTextNode(String(arg)) | |
); | |
}); | |
return frag; | |
}; | |
polyfillAll( | |
[ | |
Element.prototype, | |
Document.prototype, | |
DocumentFragment.prototype | |
], | |
{ | |
append(...args) { | |
this.appendChild(addToFrag(...args)); | |
} | |
prepend(...args) { | |
this.insertBefore(addToFrag(...args), this.firstChild); | |
} | |
} | |
); | |
polyfill(Element.prototype, "closest", (selector) => { | |
let element = this; | |
let closest = null; | |
if (document.documentElement.contains(element)) { | |
do { | |
if (element.matches(selector)) { | |
closest = element; | |
break; | |
} | |
element = element.parentElement || element.parentNode; | |
} while (element !== null); | |
} | |
return closest; | |
}); | |
polyfillAll( | |
[ | |
Element.prototype, | |
CharacterData.prototype, | |
DocumentType.prototype | |
] | |
{ | |
before(...args) { | |
this.parentNode.insertBefore(addToFrag(...args), this); | |
} | |
after(...args) { | |
this.parentNode.insertBefore(addToFrag(...args), this.nextSibling); | |
} | |
remove() { | |
if (this.parentNode) { | |
this.parentNode.removeChild(this); | |
} | |
} | |
replaceWith(...args) { | |
// I only THINK this is a complete polyfill. Kinda hard to follow | |
// the MDN example. | |
this.before(...args); | |
this.remove(); | |
} | |
} | |
); | |
// NodeList.prototype.forEach.length = 1 | |
polyfill(NodeList.prototype, "forEach", (...args) => { | |
Array.prototype.forEach.apply(this, args); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
polyfillAll
methods (before
,replaceWith
etc.) should have alength
of0