Last change
on this file since fa375fe was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
515 bytes
|
Line | |
---|
1 | module.exports = function flatten(list, depth) {
|
---|
2 | depth = (typeof depth == 'number') ? depth : Infinity;
|
---|
3 |
|
---|
4 | if (!depth) {
|
---|
5 | if (Array.isArray(list)) {
|
---|
6 | return list.map(function(i) { return i; });
|
---|
7 | }
|
---|
8 | return list;
|
---|
9 | }
|
---|
10 |
|
---|
11 | return _flatten(list, 1);
|
---|
12 |
|
---|
13 | function _flatten(list, d) {
|
---|
14 | return list.reduce(function (acc, item) {
|
---|
15 | if (Array.isArray(item) && d < depth) {
|
---|
16 | return acc.concat(_flatten(item, d + 1));
|
---|
17 | }
|
---|
18 | else {
|
---|
19 | return acc.concat(item);
|
---|
20 | }
|
---|
21 | }, []);
|
---|
22 | }
|
---|
23 | };
|
---|
Note:
See
TracBrowser
for help on using the repository browser.