Created
September 27, 2019 15:42
-
-
Save andygimma/bfcb3ae4fb53eb432ea2538190241a21 to your computer and use it in GitHub Desktop.
Flatten array
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
describe("flatten an array of arbitrarily nested arrays of integers into a flat array of integers", function () { | |
it("Should return empty array when given empty array provided", function () { | |
expect(flatten([])).toEqual([]); | |
}); | |
it("Should return a flat array when given a flat array provided", function () { | |
expect(flatten([1])).toEqual([1]); | |
}); | |
it("Should return an empty array when given undefined", function () { | |
expect(flatten(undefined)).toEqual([]); | |
}); | |
it("Should 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,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,2,3,4] on [[1,2,[3],4]] provided", function () { | |
expect(flatten([[1, 2, [3], 4]])).toEqual([1, 2, 3, 4]); | |
}); | |
}); | |
function flatten(arr) { | |
if (!Array.isArray(arr)) return []; | |
return arr.reduce(function (acc, x) { | |
return acc.concat(Array.isArray(x) ? flatten(x) : [x]); | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment