Merge pull request #532 from Chalarangelo/flatten-fix

[FIX: #525] Flatten fix
This commit is contained in:
Angelos Chalaris
2018-01-11 10:56:25 +02:00
committed by GitHub
5 changed files with 16 additions and 23 deletions

View File

@ -1,13 +1,20 @@
### flatten
Flattens an array.
Flattens an array up to the specified depth.
Use a new array, `Array.concat()` and the spread operator (`...`) to cause a shallow denesting of any contained arrays.
Use recursion, decrementing `depth` by 1 for each level of depth.
Use `Array.reduce()` and `Array.concat()` to merge elements or arrays.
Base case, for `depth` equal to `1` stops recursion.
Omit the second argument, `depth` to flatten only to a depth of `1` (single flatten).
```js
const flatten = arr => [].concat(...arr);
const flatten = (arr, depth = 1) =>
depth != 1
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);
```
```js
flatten([1, [2], 3, 4]); // [1,2,3,4]
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
```

View File

@ -1 +1,4 @@
module.exports = flatten = arr => [].concat(...arr);
module.exports = flatten = (arr, depth = 1) =>
depth != 1
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);

View File

@ -6,6 +6,7 @@ test('Testing flatten', (t) => {
//Please go to https://github.com/substack/tape
t.true(typeof flatten === 'function', 'flatten is a Function');
t.deepEqual(flatten([1, [2], 3, 4]), [1, 2, 3, 4], "Flattens an array");
t.deepEqual(flatten([1, [2, [3, [4, 5], 6], 7], 8], 2), [1, 2, 3, [4, 5], 6, 7, 8], "Flattens an array");
//t.deepEqual(flatten(args..), 'Expected');
//t.equal(flatten(args..), 'Expected');
//t.false(flatten(args..), 'Expected');

View File

@ -1,4 +0,0 @@
module.exports = flattenDepth = (arr, depth = 1) =>
depth != 1
? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), [])
: arr.reduce((a, v) => a.concat(v), []);

View File

@ -1,14 +0,0 @@
const test = require('tape');
const flattenDepth = require('./flattenDepth.js');
test('Testing flattenDepth', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof flattenDepth === 'function', 'flattenDepth is a Function');
t.deepEqual(flattenDepth([1, [2], 3, 4]), [1, 2, 3, 4], "Flattens an array up to the specified depth");
//t.deepEqual(flattenDepth(args..), 'Expected');
//t.equal(flattenDepth(args..), 'Expected');
//t.false(flattenDepth(args..), 'Expected');
//t.throws(flattenDepth(args..), 'Expected');
t.end();
});