Last active
December 8, 2019 14:16
-
-
Save frycz/5944c64f9c40b232b6345aef7445a2f3 to your computer and use it in GitHub Desktop.
Function flattens an array of arbitrarily nested arrays of integers into a flat array of integers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Flattens an array of arbitrarily nested arrays of integers into a flat array of integers. | |
* Run `jest ./flattenArray.test.js` for tests. | |
* | |
* @param {*} arr - nested array of integers | |
* @returns flattened array | |
*/ | |
function flattenArray(arr) { | |
const result = []; | |
arr.forEach(elem => { | |
if (Array.isArray(elem)) { | |
result.push(...flattenArray(elem)); | |
} else { | |
result.push(elem); | |
} | |
}); | |
return result; | |
} | |
module.exports = flattenArray; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const flattenArray = require("./flattenArray"); | |
describe("flattenArray", () => { | |
it("should map flat array to flat array", () => { | |
expect(flattenArray([])).toEqual([]); | |
expect(flattenArray([1, 2, 3])).toEqual([1, 2, 3]); | |
}); | |
it("should flatten nested array to flat array", () => { | |
expect(flattenArray([1, 2, [3, 4, [5, 6, 7], 8, 9]])).toEqual([ | |
1, | |
2, | |
3, | |
4, | |
5, | |
6, | |
7, | |
8, | |
9 | |
]); | |
expect(flattenArray([1, 2, [], 3, [4, [], 5], 6])).toEqual([ | |
1, | |
2, | |
3, | |
4, | |
5, | |
6 | |
]); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { verbose: true }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment