Skip to content

Instantly share code, notes, and snippets.

@moshensky
Created March 13, 2017 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moshensky/3c812fd49719a2c485dd196c066642bd to your computer and use it in GitHub Desktop.
Save moshensky/3c812fd49719a2c485dd196c066642bd to your computer and use it in GitHub Desktop.
Flat an array of arbitrarily nested arrays into a flat array (ES6)
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);
}
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