Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Core: Use Array#flat where supported #4459

Closed
wants to merge 14 commits into from
6 changes: 3 additions & 3 deletions src/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ define( [
"./var/arr",
"./var/getProto",
"./var/slice",
"./var/concat",
"./var/flat",
"./var/push",
"./var/indexOf",
"./var/class2type",
Expand All @@ -19,7 +19,7 @@ define( [
"./var/isWindow",
"./core/DOMEval",
"./core/toType"
], function( arr, getProto, slice, concat, push, indexOf,
], function( arr, getProto, slice, flat, push, indexOf,
class2type, toString, hasOwn, fnToString, ObjectFunctionString,
trim, support, isWindow, DOMEval, toType ) {

Expand Down Expand Up @@ -395,7 +395,7 @@ jQuery.extend( {
}

// Flatten any nested arrays
return concat.apply( [], ret );
return flat.call( ret );
mgol marked this conversation as resolved.
Show resolved Hide resolved
},

// A global GUID counter for objects
Expand Down
14 changes: 14 additions & 0 deletions src/var/flat.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
define( [
"./arr",
"./concat"
], function( arr, concat ) {
"use strict";
aelafifi marked this conversation as resolved.
Show resolved Hide resolved

return arr.flat ? function() {
aelafifi marked this conversation as resolved.
Show resolved Hide resolved

// Flat with depth = 1 to give the same result of concat.apply.
return arr.flat.call( this, 1 );
} : function() {
return concat.apply( [], this );
};
} );
13 changes: 12 additions & 1 deletion test/unit/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ QUnit.test( "map()", function( assert ) {
} );

QUnit.test( "jQuery.map", function( assert ) {
assert.expect( 25 );
assert.expect( 28 );

var i, label, result, callback;

Expand Down Expand Up @@ -791,6 +791,17 @@ QUnit.test( "jQuery.map", function( assert ) {
return k % 2 ? k : [ k, k, k ];
} );
assert.equal( result.join( "" ), "00012223", "Array results flattened (#2616)" );

result = jQuery.map( [ [ [ 1, 2 ], 3 ], 4 ], function( v, k ) {
return v;
} );
assert.equal( result.length, 3, "Array flatten only one level down" );
assert.ok( Array.isArray( result[ 0 ] ), "Array flatten only one level down" );

result = jQuery.map( Array( 300000 ), function( v, k ) {
return k;
} );
assert.equal( result.length, 300000, "Able to map 300000 records without any problems (#4320)" );
aelafifi marked this conversation as resolved.
Show resolved Hide resolved
} );

QUnit.test( "jQuery.merge()", function( assert ) {
Expand Down