Created
January 3, 2018 15:58
-
-
Save b2rsp/c584a48f2e6593d4bd58ac00b9d948be to your computer and use it in GitHub Desktop.
Tests for a function that flatten an nested arrays of integers into a flat array of integers. (ES6 required)
This file contains hidden or 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
| describe("Flatten an nested arrays of integers into a flat array of integers.", function() { | |
| it("Return an empty array when empty array provided", function() { | |
| expect(flatten([])).toEqual([]); | |
| }); | |
| it("Return a flat array when a flat array is provided", function() { | |
| expect(flatten([4, 5])).toEqual([4, 5]); | |
| }); | |
| it("Return [1,2,3,4] on [[1,2,[3]],4] provided", function() { | |
| expect(flatten([[1,2,[3]],4])).toEqual([1,2,3,4]); | |
| }); | |
| it("Should return [1,4,9,0] on [[[1], [4]], [9], [[[0]]]] provided", function() { | |
| expect(flatten([[[1], [4]], [9], [[[0]]]])).toEqual([1,4,9,0]); | |
| }); | |
| }); | |
| function flatten (rawArray, flattenArray = []) { | |
| if (! (rawArray instanceof Array)) throw Error('Param passed is not an array'); | |
| rawArray.forEach((value) => { | |
| if (typeof value === 'number') { | |
| flattenArray.push(value); | |
| } else if (value instanceof Array) { | |
| flatten(value, flattenArray); | |
| } else { | |
| throw Error('Value passed is not an array or integer'); | |
| } | |
| }); | |
| return flattenArray; | |
| }; | |
| jasmineRunner.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment