Skip to content

Instantly share code, notes, and snippets.

@tobiasoberrauch
Forked from eliperelman/LICENSE.txt
Last active August 29, 2015 14:26
Show Gist options
  • Save tobiasoberrauch/b5ac00303d7a1e649816 to your computer and use it in GitHub Desktop.
Save tobiasoberrauch/b5ac00303d7a1e649816 to your computer and use it in GitHub Desktop.
140byt.es polyfill for Array.filter

140byt.es polyfill for Array.filter

Thanks to atk and jdalton for making the solution more robust and compliant! :)

[].filter || (Array.prototype.filter = // Use the native array filter method, if available.
function(a, //a function to test each value of the array against. Truthy values will be put into the new array and falsy values will be excluded from the new array
b, // placeholder
c, // placeholder
d, // placeholder
e // placeholder
) {
c = this; // cache the array
d = []; // array to hold the new values which match the expression
for (e in c) // for each value in the array,
~~e + '' == e && e >= 0 && // coerce the array position and if valid,
a.call(b, c[e], +e, c) && // pass the current value into the expression and if truthy,
d.push(c[e]); // add it to the new array
return d // give back the new array
})
[].filter||(Array.prototype.filter=function(a,b,c,d,e){c=this;d=[];for(e in c)~~e+''==e&&e>=0&&a.call(b,c[e],+e,c)&&d.push(c[e]);return d})
DO WHAT THE **** YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Eli Perelman http://eliperelman.com
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE **** YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE **** YOU WANT TO.
{
"name": "arrayFilter140Polyfill",
"description": "A tweet-sized polyfill for Array.prototype.filter",
"keywords": [
"array",
"filter",
"polyfill",
"prototype"
]
}
<!DOCTYPE html>
<title>Array filter polyfill</title>
<div>Expected value: filter the array values outside of our range (less than 6)</div>
<script>
[].filter||(Array.prototype.filter=function(a,b,c,d,e){c=this;d=[];for(e in c)~~e+''==e&&e>=0&&a.call(b,c[e],+e,c)&&d.push(c[e]);return d});
var arr = [1,2,3,4,5,6,7,8,9,10];
// creates new array of [1,2,3,4,5] and reassigns it to arr.
arr = arr.filter(function(value) {
return value < 6;
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment