Skip to content

Instantly share code, notes, and snippets.

@hannesvdvreken
Last active February 8, 2020 19:10
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 hannesvdvreken/6f77fbb793ac0e300d7c11b86d789569 to your computer and use it in GitHub Desktop.
Save hannesvdvreken/6f77fbb793ac0e300d7c11b86d789569 to your computer and use it in GitHub Desktop.
import assert from "assert";
function flatten<T>(array: (T|T[])[]): T[] {
let flat: T[] = [];
for (const el of array) {
if (!Array.isArray(el)) {
flat.push(el);
} else {
flat.push(...flatten(el));
}
}
return flat;
}
describe("flatten function", function() {
it("returns empty on empty input", function() {
assert.equal(flatten([]), []);
});
it("remains normal when given one level", function() {
assert.equal(flatten([1, 2, 3]), [1, 2, 3]);
});
it("flattens a multi level array", function() {
assert.equal(flatten([1, [2], 3]), [1, 2, 3]);
});
it("flattens a very deep complex array", function() {
assert.equal(flatten([1, [[[[2, 3]]], 4], 5]), [1, 2, 3, 4, 5]);
});
it("works when given any type", function() {
assert.equal(flatten(["a", ["b"], "c"]), ["a", "b", "c"]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment