Created
March 30, 2020 15:29
-
-
Save cferdinandi/e3bc14f7d9dece812d4124b9609ee3ea to your computer and use it in GitHub Desktop.
Polyfill examples
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
<!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> |
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
<!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