Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]);
- }, []);
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement