Last active
February 8, 2020 19:10
-
-
Save hannesvdvreken/6f77fbb793ac0e300d7c11b86d789569 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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