Skip to content

Instantly share code, notes, and snippets.

@jed
Forked from 140bytes/LICENSE.txt
Created June 17, 2011 14:51
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jed/1031568 to your computer and use it in GitHub Desktop.
Save jed/1031568 to your computer and use it in GitHub Desktop.
polyfill an ES5-ish Array.prototype.map
// based loosely on Kris Kowal's es-5shim.js
// https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js#L204
//
// due to space constraints, this version does not check function type or cast length to a number
[].map || ( // if arrays have no map
Array.prototype.map = // set the prototype's map
function( // to a function
a // that takes a mapping function
/*, thisp */ // and an optional scope.
){
for (
var b = this // cache `this` and
, c = b.length // the array's length,
, d = [] // create the return array
, e = 0 // and initialize the cursor,
, f // and cache undefined.
; e < b; // while the cursor is less than the length
) d[e] = // set the result member
e in b // if it originally exists,
? a.call( // to the given function, called with
arguments[1], // the optional scope,
b[e], // existing member,
e++, // member index, and
b ) // current scope,
: f; // or to undefined otherwise.
return d // return the result.
})
[].map||(Array.prototype.map=function(a){for(var b=this,c=b.length,d=[],e=0,f;e<b;)d[e]=e in b?a.call(arguments[1],b[e],e++,b):f;return d})
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Jed Schmidt <http://jed.is>
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 FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "map",
"description": "polyfill an ES5-compatibile Array.prototype.map where needed.",
"keywords": [
"array",
"map",
"es5",
"polyfill"
]
}
<!DOCTYPE html>
<title>Foo</title>
<div>Expected value: <b>2,4,6,8</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var map =
[].map||(Array.prototype.map=function(a){for(var b=this,c=b.length,d=[],e=0,f;e<b;)d[e]=e in b?a.call(arguments[1],b[e],e++,b):f;return d})
document.getElementById( "ret" ).innerHTML = map.call([1,2,3,4], function(x){ return x*2 })
</script>
@Daniel-Hug
Copy link

@atk Found a typo in your version (you misspelled length as lengh). So just in case anyone wishes to use your version of the snippet, here it is fixed:

[].map||(Array.prototype.map=function(a,t){for(var c=this,b=c.length,d=[],e=0;e<b;)e in c&&(d[e]=a.call(t,c[e],e++,c));d.length=b;return d})

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