twitst4tz

twitter statistics web application
Log | Files | Refs | README | LICENSE

array-flatten.js (1195B)


      1 'use strict'
      2 
      3 /**
      4  * Expose `arrayFlatten`.
      5  */
      6 module.exports = arrayFlatten
      7 
      8 /**
      9  * Recursive flatten function with depth.
     10  *
     11  * @param  {Array}  array
     12  * @param  {Array}  result
     13  * @param  {Number} depth
     14  * @return {Array}
     15  */
     16 function flattenWithDepth (array, result, depth) {
     17   for (var i = 0; i < array.length; i++) {
     18     var value = array[i]
     19 
     20     if (depth > 0 && Array.isArray(value)) {
     21       flattenWithDepth(value, result, depth - 1)
     22     } else {
     23       result.push(value)
     24     }
     25   }
     26 
     27   return result
     28 }
     29 
     30 /**
     31  * Recursive flatten function. Omitting depth is slightly faster.
     32  *
     33  * @param  {Array} array
     34  * @param  {Array} result
     35  * @return {Array}
     36  */
     37 function flattenForever (array, result) {
     38   for (var i = 0; i < array.length; i++) {
     39     var value = array[i]
     40 
     41     if (Array.isArray(value)) {
     42       flattenForever(value, result)
     43     } else {
     44       result.push(value)
     45     }
     46   }
     47 
     48   return result
     49 }
     50 
     51 /**
     52  * Flatten an array, with the ability to define a depth.
     53  *
     54  * @param  {Array}  array
     55  * @param  {Number} depth
     56  * @return {Array}
     57  */
     58 function arrayFlatten (array, depth) {
     59   if (depth == null) {
     60     return flattenForever(array, [])
     61   }
     62 
     63   return flattenWithDepth(array, [], depth)
     64 }