Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@cferdinandi
Created March 30, 2020 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cferdinandi/e3bc14f7d9dece812d4124b9609ee3ea to your computer and use it in GitHub Desktop.
Save cferdinandi/e3bc14f7d9dece812d4124b9609ee3ea to your computer and use it in GitHub Desktop.
Polyfill examples
<!DOCTYPE html>
<html>
<head>
<title>Array.find()</title>
</head>
<body>
<script>
//
// IE9 Support
//
// if the Array.prototype.find() method does not exist
if (!Array.prototype.find) {
// create a new function with that name
Array.prototype.find = function (callback) {
// pass the callback into the Array.prototype.filter() method
// it accepts the same arguments as Array.prototype.find()
var matches = this.filter(callback);
// if there are matches, return the first one
if (matches.length) {
return matches[0];
}
// otherwise, return undefined
return undefined;
};
}
//
// IE6 Support
//
// if the Array.prototype.find() method does not exist
if (!Array.prototype.find) {
// create a new function with that name
Array.prototype.find = function (callback) {
// Loop through the array
for (var i = 0; i < this.length; i++) {
// Check if the current element matches
var match = callback(this[i], i, this);
// If the current element matches, return it
if (match) {
return this[i];
}
}
// Otherwise, return undefined
return undefined;
};
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>String.includes()</title>
</head>
<body>
<script>
// if the String.prototype.includes() method does not exist
if (!String.prototype.includes) {
// create a new function with that name
String.prototype.includes = function (search, pos) {
// if a position was provided, use it
// otherwise, use 0
pos = pos || 0;
// use the more backwards compatible String.indexOf() method to get the substring's index
// check if that index is greater than -1 and return the result
return this.indexOf(search, pos) > -1;
};
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment