diff --git a/17_flatten/README.md b/17_flatten/README.md new file mode 100644 index 00000000000..c1544421cdb --- /dev/null +++ b/17_flatten/README.md @@ -0,0 +1,11 @@ +# Exercise 17 - flatten + +Write a function that takes in an array of positive integers and an optional depth argument which defaults to `Infinity` if not specified. + +The function returns a new array with all sub-array elements concatenated into it recursively up to the specified depth. + +```javascript +flatten([[1, 2], [3, 4]]); // Output: [1, 2, 3, 4] +flatten([[1, [8, 9]], [3, 4]], 2); // Output: [1, [8, 9], 3, 4] +flatten([2, 4, 6]); // Output: [2, 4, 6] +``` diff --git a/17_flatten/flatten.js b/17_flatten/flatten.js new file mode 100644 index 00000000000..91f21103161 --- /dev/null +++ b/17_flatten/flatten.js @@ -0,0 +1,6 @@ +const flatten = function() { + +}; + +// Do not edit below this line +module.exports = flatten; diff --git a/17_flatten/flatten.spec.js b/17_flatten/flatten.spec.js new file mode 100644 index 00000000000..b8c64ccbcaf --- /dev/null +++ b/17_flatten/flatten.spec.js @@ -0,0 +1,15 @@ +const flatten = require('./flatten'); + +describe('flatten', () => { + test('First test description', () => { + // Replace this comment with any other necessary code, and update the expect line as necessary + + expect(flatten()).toBe(''); + }); + + test.skip('Second test description', () => { + // Replace this comment with any other necessary code, and update the expect line as necessary + + expect(flatten()).toBe(''); + }); +}); diff --git a/17_flatten/solution/flatten-solution.js b/17_flatten/solution/flatten-solution.js new file mode 100644 index 00000000000..5e1c2782cc4 --- /dev/null +++ b/17_flatten/solution/flatten-solution.js @@ -0,0 +1,13 @@ +const flatten = function (array, depth = Infinity) { + if (depth === 0 || !array.some(Array.isArray)) return array + + let flattened = [] + array.forEach(el => { + flattened = flattened.concat(el) + }); + + return flatten(flattened, depth - 1) +} + +// Do not edit below this line +module.exports = flatten; diff --git a/17_flatten/solution/flatten-solution.spec.js b/17_flatten/solution/flatten-solution.spec.js new file mode 100644 index 00000000000..5b262667bb1 --- /dev/null +++ b/17_flatten/solution/flatten-solution.spec.js @@ -0,0 +1,17 @@ +const flatten = require('./flatten-solution'); + +describe('flatten', () => { + test('Works', () => { + expect(flatten([[1, [2, 3]], 4], 1)).toEqual([1, [2, 3], 4]) + }) + test('Works with a depth argument', () => { + expect(flatten([ [1, 2], [3, 4, [[1, [8, 9]], [3, 4]], 2] ], 2)).toEqual([1, 2, 3, 4, [1, [ 8, 9 ]], [3, 4], 2]); + }); + + test('Works with no depth argument', () => { + expect(flatten([[[1, 2], [3, 4]], 1, [[[[[[[[1]]]]], 4, [[[[[[5, 4]]]]]], 1]]]])).toEqual([1, 2, 3, 4, 1, 1, 4, 5, 4, 1]); + }); + test('Works with an empty array', () => { + expect(flatten([])).toEqual([]); + }); +});