Merge branch 'bug_2616' of https://github.com/jboesch/jquery into map-object.1.6

* 'bug_2616' of https://github.com/jboesch/jquery:
  Bug 2616; Adding object support to jQuery.map
This commit is contained in:
Dan Heberden 2011-03-21 08:04:35 -07:00
commit f0e7d28e83
2 changed files with 26 additions and 14 deletions

View file

@ -706,15 +706,29 @@ jQuery.extend({
// arg is for internal usage only // arg is for internal usage only
map: function( elems, callback, arg ) { map: function( elems, callback, arg ) {
var ret = [], value; var ret = [],
value,
length = elems.length,
// same object detection used in jQuery.each, not full-proof but very speedy.
isObj = length === undefined;
// Go through the array, translating each of the items to their if ( isObj ) {
// new value (or values). for ( key in elems ) {
for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ key ], key, arg );
value = callback( elems[ i ], i, arg );
if ( value != null ) { if ( value != null ) {
ret[ ret.length ] = value; ret[ ret.length ] = value;
}
}
} else {
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
} }
} }

View file

@ -608,7 +608,7 @@ test("first()/last()", function() {
}); });
test("map()", function() { test("map()", function() {
expect(2);//expect(6); expect(6);
same( same(
jQuery("#ap").map(function(){ jQuery("#ap").map(function(){
@ -626,25 +626,23 @@ test("map()", function() {
"Single Map" "Single Map"
); );
return;//these haven't been accepted yet
//for #2616 //for #2616
var keys = jQuery.map( {a:1,b:2}, function( v, k ){ var keys = jQuery.map( {a:1,b:2}, function( v, k ){
return k; return k;
}, [ ] ); });
equals( keys.join(""), "ab", "Map the keys from a hash to an array" ); equals( keys.join(""), "ab", "Map the keys from a hash to an array" );
var values = jQuery.map( {a:1,b:2}, function( v, k ){ var values = jQuery.map( {a:1,b:2}, function( v, k ){
return v; return v;
}, [ ] ); });
equals( values.join(""), "12", "Map the values from a hash to an array" ); equals( values.join(""), "12", "Map the values from a hash to an array" );
var scripts = document.getElementsByTagName("script"); var scripts = document.getElementsByTagName("script");
var mapped = jQuery.map( scripts, function( v, k ){ var mapped = jQuery.map( scripts, function( v, k ){
return v; return v;
}, {length:0} ); });
equals( mapped.length, scripts.length, "Map an array(-like) to a hash" ); equals( mapped.length, scripts.length, "Map an array(-like) to a hash" );