Skip to content

Instantly share code, notes, and snippets.

@andygimma
Created September 27, 2019 15:42
Show Gist options
  • Save andygimma/bfcb3ae4fb53eb432ea2538190241a21 to your computer and use it in GitHub Desktop.
Save andygimma/bfcb3ae4fb53eb432ea2538190241a21 to your computer and use it in GitHub Desktop.
Flatten array
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