@@ -465,40 +465,60 @@ function _unsqueeze (array, dims, dim) {
465465 * Flatten a multi dimensional array, put all elements in a one dimensional
466466 * array
467467 * @param {Array } array A multi dimensional array
468+ * @param {boolean } [isHomogeneous=false] Indicates if the size is homogeneous (like a valid matrix)
468469 * @return {Array } The flattened array (1 dimensional)
469470 */
470- export function flatten ( array ) {
471+ export function flatten ( array , isHomogeneous = false ) {
471472 if ( ! Array . isArray ( array ) ) {
472473 // if not an array, return as is
473474 return array
474475 }
475- if ( typeof Array . prototype . flat === 'function' ) {
476- return array . flat ( Infinity )
476+ if ( isHomogeneous ) {
477+ return _flattenHomogeneous ( array )
477478 } else {
478- // TODO: once Array.prototype.flat is supported in all browsers, remove this and the _flatten function
479- return _flatten ( array )
479+ if ( typeof Array . prototype . flat === 'function' ) {
480+ return array . flat ( Infinity )
481+ } else {
482+ return _flattenFallback ( array )
483+ }
480484 }
481485
482- function _flatten ( array ) {
486+ function _flattenFallback ( arr ) {
487+ // remove this when Array.prototype.flat is broadly supported
483488 const flat = [ ]
484-
485- function flattenHelper ( value ) {
489+ _recurse ( arr )
490+ return flat
491+ function _recurse ( value ) {
486492 if ( Array . isArray ( value ) ) {
487493 const len = value . length
488494 for ( let i = 0 ; i < len ; i ++ ) {
489- flattenHelper ( value [ i ] ) // traverse through sub-arrays recursively
495+ _recurse ( value [ i ] ) // traverse through sub-arrays recursively
490496 }
491497 } else {
492498 flat . push ( value )
493499 }
494500 }
501+ }
495502
496- const len = array . length
497- for ( let i = 0 ; i < len ; i ++ ) {
498- flattenHelper ( array [ i ] )
499- }
500-
503+ function _flattenHomogeneous ( arr ) {
504+ const flat = [ ]
505+ _recurse ( arr )
501506 return flat
507+
508+ function _recurse ( value ) {
509+ if ( Array . isArray ( value ) ) {
510+ const len = value . length
511+ if ( Array . isArray ( value [ 0 ] ) ) {
512+ for ( let i = 0 ; i < len ; i ++ ) {
513+ _recurse ( value [ i ] ) // traverse through sub-arrays recursively
514+ }
515+ } else {
516+ for ( let i = 0 ; i < len ; i ++ ) {
517+ flat . push ( value [ i ] ) // traverse through sub-arrays without recursion
518+ }
519+ }
520+ }
521+ }
502522 }
503523}
504524
0 commit comments