Last active
August 25, 2016 15:28
-
-
Save masaeedu/260ce5e0d982c3653465a9323c9644fa to your computer and use it in GitHub Desktop.
Flattening function for arbitrarily nested arrays in TypeScript 2.1
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
// Note: Prefer static typing over defensive programming, lots of tests | |
// Note: The simple recursive impl. here is sufficient when dealing with small input (e.g unwrapping JSON), for potentially large input the recursion should be unrolled | |
interface Nested<T> extends Array<T | Nested<T>> { } | |
function* flatten<T>(items: Nested<T>): Iterable<T> { | |
for (var i of items) | |
if (Array.isArray(i)) yield* flatten(i); | |
else yield i; | |
} | |
// Tests | |
console.log(Array.from(flatten([]))); // [] Empty array | |
console.log(Array.from(flatten([[1,2,[3, [1, 2, 1, 3]]],4]))) // [ 1, 2, 3, 1, 2, 1, 3, 4 ] Sample input | |
console.log(Array.from(flatten(["hello", ["world"]]))); // [ "hello", "world" ] Array of iterables | |
// Runtime errors | |
const a: any[] = []; | |
a.push(a); | |
Array.from(flatten(a)); // Stack overflow | |
// Compile errors | |
flatten(); // empty | |
flatten(null); // null with --strictNullChecks enabled | |
flatten(10); // non-array | |
flatten(""); // other iterable |
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
Show hidden characters
{ | |
"compilerOptions": { | |
"module": "commonjs", | |
"target": "es2015", | |
"noImplicitAny": true, | |
"sourceMap": false, | |
"strictNullChecks": true | |
}, | |
"files": [ | |
"main.ts" | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment