Merge pull request #532 from Chalarangelo/flatten-fix
[FIX: #525] Flatten fix
This commit is contained in:
@ -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]
|
||||
```
|
||||
|
||||
@ -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), []);
|
||||
@ -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');
|
||||
|
||||
@ -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), []);
|
||||
@ -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();
|
||||
});
|
||||
Reference in New Issue
Block a user