jQuery: The Write Less, Do More JavaScript Library

Ticket #2616 (new enhancement)

Opened 5 months ago

Last modified 4 months ago

A better jQuery.map

Reported by: flesler Assigned to: anonymous
Type: enhancement Priority: major
Milestone: 1.2.4 Component: core
Version: 1.2.3 Keywords: array map
Cc: Needs: Commit

Description

Hi, today I realized jQuery.map doesn't support hashes(associative arrays). I'm surprised, this is a behavior I'd assume it'd be included.

I added the changes to make this possible. In addition, added a third, optional, argument that is the return object. So it's possible to map on a existing object.

I made it so flexible, that one can map from an array to a hash, and the other way around as well. This is mostly useful to collect the keys or values from a hash, or to map an array of elements to an object(like setArray). It will handle array-like objects, and will treat them as arrays

I optimized the array concatenation, so now it's only done once, in the end, and now, there's no need for array-wrapping the returned data.

I think the length of the code remains more or less the same, so this should be doable.

I tested all the cases in IE6, FF2, Safari 3, and Opera 9.

I hope this helps

Attachments

map.diff (1.3 kB) - added by flesler 5 months ago.
Proposal
map-tests.diff (1.1 kB) - added by flesler 4 months ago.
The tests for the test suite
map[5753].diff (1.1 kB) - added by flesler 2 months ago.
Updated to match against [5753]

Change History

Changed 5 months ago by flesler

Proposal

Changed 5 months ago by flesler

Tried all these cases in IE6, FF2, Opera 9.25 and Safari 3 and they all worked well.

var keys = $.map( {a:1,b:2}, function( v, k ){
	return k;
}, [ ] );
alert(keys);
var values = $.map( {a:1,b:2}, function( v, k ){
	return v;
}, [ ] );
alert(values);
var mapped = $.map( document.getElementsByTagName('script'), function( v, k ){
	return v;
}, {length:0} );
alert(mapped);
var flat = $.map( Array(8), function( v, k ){
	return k % 2 ? k : [k,k,k];//try mixing array and regular returns
});
alert(flat);

Changed 4 months ago by joern

Could you convert that to the testsuite, too?

Changed 4 months ago by flesler

The tests for the test suite

Changed 4 months ago by joern

  • need changed from Review to Commit

Commited test in [5342].

Changed 4 months ago by joern

Your patch must be tested against the benchmark before applying it, as map is a core function of jQuery. Its raw speed has higher priority then being useful for other cases. If we can do both, even better.

Changed 4 months ago by flesler

Shouldn't you/we accept the change before adding the tests to the test suite ? Or it will fail for others that haven't applied the proposed diff.

Changed 4 months ago by flesler

I meant you/we add the test, not accept. I didn't mean to say it's on me to accept :)

Changed 2 months ago by flesler

Updated to match against [5753]

Note: See TracTickets for help on using tickets.