Skip to content

Instantly share code, notes, and snippets.

@leecade
Forked from jed/LICENSE.txt
Created October 8, 2011 14:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leecade/1272344 to your computer and use it in GitHub Desktop.
Save leecade/1272344 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)
e // (placeholder)
){
c = a.length; // get the length of the object.
if ( // it's an array if
c >= 0 // the length is zero or a positive integer,
) for ( // so loop by
e = [], // caching the target array,
d = 0; // initializing the cursor, and
d < c; // until the cursor reaches the length
d++ // by increments,
) e[d] = // push to the array
b(a[d], d); // the results of the map function
else { // otherwise, if the object has no length
e = {}; // cache the target object, and
for ( // for
d // each property
in a // in the source object
) e[d] = // set the same on the target object with
b(a[d],d) // the results of the map function
}
return e // finally, return the target object
}
function(a,b,c,d,e){c=a.length;if(c>=0)for(e=[],d=0;d<c;d++)e[d]=b(a[d],d);else{e={};for(d in a)e[d]=b(a[d],d)}return e}
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",
"keywords": ["map", "array", "arrays", "functional"]
}
// Define the map function
var map = function(a,b,c,d,e){c=a.length;if(c>=0)for(e=[],d=0;d<c;d++)e.push(b(a[d],d));else{e={};for(d in a)e[d]=b(a[d],d)}return e}
// 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' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment