Skip to content

Instantly share code, notes, and snippets.

@james-jlo-long
Last active July 24, 2018 10:29
Show Gist options
  • Save james-jlo-long/138d3bea767e46e45333b0e3e16e4b64 to your computer and use it in GitHub Desktop.
Save james-jlo-long/138d3bea767e46e45333b0e3e16e4b64 to your computer and use it in GitHub Desktop.
A simple library for polyfilling missing functionality in older browsers
/**
* Polyfills a property on the given object. If the object already has the
* property, no action is taken.
*
* @param {?} object
* Object whose property should be polyfilled.
* @param {String} name
* Name of the property to polyfill.
* @param {?} value
* Value for the property.
* @param {Boolean} [force=false]
* If true, the change will be forcably applied. If false, the change
* will only be applied if the property isn't a match.
*/
function polyfill(object, name, value, force) {
if (force || typeof object[name] !== typeof value) {
Object.defineProperty(object, name, {
value: value,
configurable: true,
enumerable: false,
writable: true
});
}
}
/**
* Polyfills multiple properties onto one or more objects.
*
* @param {Array<?>|?} objects
* Either the object to polyfill or an array of objects to polyfill.
* @param {Object} methods
* Methods to polyfill.
* @param {Boolean} [force=false]
* If true, the changes will be forcably applied. If false, the changes
* will only be applied if the property isn't a match.
*/
function polyfillAll(objects, methods, force) {
if (!Array.isArray(objects) || objects === Array.prototype) {
objects = [objects];
}
objects.forEach(function (object) {
Object
.keys(methods)
.forEach(function (key) {
polyfill(object, key, methods[key], force);
});
});
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Polyfill
polyfill(Object, "entries", function (object) {
return Object.keys(object).map(function (key) {
return [key, object[key]];
})
});
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
polyfillAll([
String.prototype,
Array.prototype
], {
includes: function (search) { // .length = 1
return this.indexOf.apply(this, arguments) > -1;
}
});
@james-jlo-long
Copy link
Author

Converted into a git repo:
https://github.com/james-jlo-long/polyfill

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment