source: trip-planner-front/node_modules/array-flatten/array-flatten.js@ 188ee53

Last change on this file since 188ee53 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 1.9 KB
Line 
1'use strict'
2
3/**
4 * Expose `arrayFlatten`.
5 */
6module.exports = flatten
7module.exports.from = flattenFrom
8module.exports.depth = flattenDepth
9module.exports.fromDepth = flattenFromDepth
10
11/**
12 * Flatten an array.
13 *
14 * @param {Array} array
15 * @return {Array}
16 */
17function flatten (array) {
18 if (!Array.isArray(array)) {
19 throw new TypeError('Expected value to be an array')
20 }
21
22 return flattenFrom(array)
23}
24
25/**
26 * Flatten an array-like structure.
27 *
28 * @param {Array} array
29 * @return {Array}
30 */
31function flattenFrom (array) {
32 return flattenDown(array, [])
33}
34
35/**
36 * Flatten an array-like structure with depth.
37 *
38 * @param {Array} array
39 * @param {number} depth
40 * @return {Array}
41 */
42function flattenDepth (array, depth) {
43 if (!Array.isArray(array)) {
44 throw new TypeError('Expected value to be an array')
45 }
46
47 return flattenFromDepth(array, depth)
48}
49
50/**
51 * Flatten an array-like structure with depth.
52 *
53 * @param {Array} array
54 * @param {number} depth
55 * @return {Array}
56 */
57function flattenFromDepth (array, depth) {
58 if (typeof depth !== 'number') {
59 throw new TypeError('Expected the depth to be a number')
60 }
61
62 return flattenDownDepth(array, [], depth)
63}
64
65/**
66 * Flatten an array indefinitely.
67 *
68 * @param {Array} array
69 * @param {Array} result
70 * @return {Array}
71 */
72function flattenDown (array, result) {
73 for (var i = 0; i < array.length; i++) {
74 var value = array[i]
75
76 if (Array.isArray(value)) {
77 flattenDown(value, result)
78 } else {
79 result.push(value)
80 }
81 }
82
83 return result
84}
85
86/**
87 * Flatten an array with depth.
88 *
89 * @param {Array} array
90 * @param {Array} result
91 * @param {number} depth
92 * @return {Array}
93 */
94function flattenDownDepth (array, result, depth) {
95 depth--
96
97 for (var i = 0; i < array.length; i++) {
98 var value = array[i]
99
100 if (depth > -1 && Array.isArray(value)) {
101 flattenDownDepth(value, result, depth)
102 } else {
103 result.push(value)
104 }
105 }
106
107 return result
108}
Note: See TracBrowser for help on using the repository browser.