TFTPaths/node_modules/array-flatten/array-flatten.js

109 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-08-19 20:00:53 +02:00
'use strict'
/**
* Expose `arrayFlatten`.
*/
2021-04-25 19:48:07 +02:00
module.exports = flatten
module.exports.from = flattenFrom
module.exports.depth = flattenDepth
module.exports.fromDepth = flattenFromDepth
2019-08-19 20:00:53 +02:00
/**
2021-04-25 19:48:07 +02:00
* Flatten an array.
*
* @param {Array} array
* @return {Array}
*/
function flatten (array) {
if (!Array.isArray(array)) {
throw new TypeError('Expected value to be an array')
}
return flattenFrom(array)
}
/**
* Flatten an array-like structure.
*
* @param {Array} array
* @return {Array}
*/
function flattenFrom (array) {
return flattenDown(array, [])
}
/**
* Flatten an array-like structure with depth.
2019-08-19 20:00:53 +02:00
*
* @param {Array} array
2021-04-25 19:48:07 +02:00
* @param {number} depth
2019-08-19 20:00:53 +02:00
* @return {Array}
*/
2021-04-25 19:48:07 +02:00
function flattenDepth (array, depth) {
if (!Array.isArray(array)) {
throw new TypeError('Expected value to be an array')
}
2019-08-19 20:00:53 +02:00
2021-04-25 19:48:07 +02:00
return flattenFromDepth(array, depth)
}
/**
* Flatten an array-like structure with depth.
*
* @param {Array} array
* @param {number} depth
* @return {Array}
*/
function flattenFromDepth (array, depth) {
if (typeof depth !== 'number') {
throw new TypeError('Expected the depth to be a number')
2019-08-19 20:00:53 +02:00
}
2021-04-25 19:48:07 +02:00
return flattenDownDepth(array, [], depth)
2019-08-19 20:00:53 +02:00
}
/**
2021-04-25 19:48:07 +02:00
* Flatten an array indefinitely.
2019-08-19 20:00:53 +02:00
*
* @param {Array} array
* @param {Array} result
* @return {Array}
*/
2021-04-25 19:48:07 +02:00
function flattenDown (array, result) {
2019-08-19 20:00:53 +02:00
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (Array.isArray(value)) {
2021-04-25 19:48:07 +02:00
flattenDown(value, result)
2019-08-19 20:00:53 +02:00
} else {
result.push(value)
}
}
return result
}
/**
2021-04-25 19:48:07 +02:00
* Flatten an array with depth.
2019-08-19 20:00:53 +02:00
*
* @param {Array} array
2021-04-25 19:48:07 +02:00
* @param {Array} result
* @param {number} depth
2019-08-19 20:00:53 +02:00
* @return {Array}
*/
2021-04-25 19:48:07 +02:00
function flattenDownDepth (array, result, depth) {
depth--
for (var i = 0; i < array.length; i++) {
var value = array[i]
if (depth > -1 && Array.isArray(value)) {
flattenDownDepth(value, result, depth)
} else {
result.push(value)
}
2019-08-19 20:00:53 +02:00
}
2021-04-25 19:48:07 +02:00
return result
2019-08-19 20:00:53 +02:00
}