@@ -501,20 +501,39 @@ function formatObject(ctx, value, recurseTimes, visibleKeys, keys) {
501
501
502
502
function formatArray ( ctx , value , recurseTimes , visibleKeys , keys ) {
503
503
var output = [ ] ;
504
- for ( var i = 0 , l = value . length ; i < l ; ++ i ) {
505
- if ( hasOwnProperty ( value , String ( i ) ) ) {
506
- output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
507
- String ( i ) , true ) ) ;
508
- } else {
509
- output . push ( '' ) ;
504
+ // if less than a tenth of the array's slots are populated, consider it sparse
505
+ // and return a compact representation. this prevents node from crashing when
506
+ // calling console.log() on a small array with large length.
507
+ // see https://github.com/nodejs/node/issues/4905
508
+ var isSparse = value . length > 10 && keys . length * 10 < value . length ;
509
+ if ( ! isSparse ) {
510
+ // output a normal dense array, eg. [ , , , "foo", "bar"]
511
+ for ( var i = 0 , l = value . length ; i < l ; ++ i ) {
512
+ if ( hasOwnProperty ( value , String ( i ) ) ) {
513
+ output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
514
+ String ( i ) , true ) ) ;
515
+ } else {
516
+ output . push ( '' ) ;
517
+ }
510
518
}
511
519
}
520
+ // output sparse arrays as eg. [10: "foo", 1000000: "bar"]
521
+ // also handle additional properties on an array, for example [1, 2, 3, foo:4]
512
522
keys . forEach ( function ( key ) {
523
+ var str = formatProperty ( ctx , value , recurseTimes , visibleKeys , key , true ) ;
513
524
if ( typeof key === 'symbol' || ! key . match ( / ^ \d + $ / ) ) {
514
- output . push ( formatProperty ( ctx , value , recurseTimes , visibleKeys ,
515
- key , true ) ) ;
525
+ output . push ( str ) ; // str in format "foo: bar"
526
+ } else if ( isSparse ) {
527
+ output . push ( key + ': ' + str ) ; // str in format "bar"
516
528
}
517
529
} ) ;
530
+ if ( isSparse ) {
531
+ if ( keys . length === 0 ) {
532
+ output . push ( '<empty array, length ' + value . length + '>' ) ;
533
+ } else {
534
+ output . push ( '<sparse array, length ' + value . length + '>' ) ;
535
+ }
536
+ }
518
537
return output ;
519
538
}
520
539
0 commit comments