Created
March 13, 2017 21:07
-
-
Save moshensky/3c812fd49719a2c485dd196c066642bd to your computer and use it in GitHub Desktop.
Flat an array of arbitrarily nested arrays into a flat array (ES6)
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
function flatten(arr, accumulator = []) { | |
if (arr.length === 0) { | |
return accumulator; | |
} | |
const [head, ...tail] = arr; | |
if (!Array.isArray(head)) { | |
return flatten(tail, accumulator.concat(head)); | |
} | |
return flatten(tail, accumulator.concat(flatten(head))); | |
} | |
export default function flatArray(arr) { | |
if (!Array.isArray(arr)) { | |
throw new Error('Argument Exception! Argument should be an array.'); | |
} | |
return flatten(arr); | |
} |
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
import { expect } from "chai"; | |
import flatArray from "../src/flat-array"; | |
describe("Flat array tests", () => { | |
describe("flatArray()", () => { | |
it("Should flat array", () => { | |
expect(flatArray([[1, 2, [3]], 4])).to.deep.equal([1, 2, 3, 4]); | |
}); | |
it("Should flat array", () => { | |
expect(flatArray([1, [2, 3, [4]]])).to.deep.equal([1, 2, 3, 4]); | |
}); | |
it("Should throw if argument is not array", () => { | |
expect(flatArray.bind({}, 'not array')).to.throw(Error); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment