Skip to content

Instantly share code, notes, and snippets.

@mikesherov
Forked from jed/LICENSE.txt
Created June 7, 2011 12:17
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 mikesherov/1012114 to your computer and use it in GitHub Desktop.
Save mikesherov/1012114 to your computer and use it in GitHub Desktop.
map properties for arrays and objects
function(
a, // source object or array
b, // map function
c, // (placeholder)
d // (placeholder)
){
d = a; // copy the object to the result, keys will be overwritten shortly
for ( // for
c // each property
in a // in the source object.. works on both arrays and objects
) d[c] = // set the same on the target object with
b(a[c],c); // the results of the map function
return d // finally, return the target object
}
function(a,b,c,d){d=a;for(c in a)d[c]=b(a[c],c);return d}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2011 Mike Sherov <http://mike.sherov.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 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",
"keywords": ["map", "array", "arrays", "functional"]
}
// Define the map function
var map = function(a,b,c,d){d=a;for(c in a)d[c]=b(a[c],c);return d}
// Define an array and a object
var arr = ["a", "b", "c", "d", "e"]
var obj = {a:0, b:1, c:2, d:3, e:4}
// Map each, returing the key/val at each
arr = map( arr, function( value, index ){ return index + value } )
obj = map( obj, function( value, index ){ return index + value } )
// Log the results:
console.log( arr ) // => [ '0a', '1b', '2c', '3d', '4e' ]
console.log( obj ) // => { a: 'a0', b: 'b1', c: 'c2', d: 'd3', e: 'e4' }
@jed
Copy link

jed commented Jun 7, 2011

hmmm, is this reliable? i'm pretty sure using for..in to iterate on an array is frowned upon.

@mikesherov
Copy link
Author

hmm, I'd love to see why it's frowned upon. Link? I think it's because of the unfiltered aspect of it, which would have also affected the object portion of the original gist. We could easily add a hasOwnProperty check which would make it more robust than the original because now objects would get that benefit too of it being filtered. What do you think?

@jed
Copy link

jed commented Jun 7, 2011

well, ideally, i'd like to have something that would roll map and filter into one for arrays and objects, where members could be mapped to a number of members from 0 to 1 for the object case and 0 to n for the array case.

@mathiasbynens, do you have any thoughts on this?

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