Skip to content

Instantly share code, notes, and snippets.

@masaeedu
Last active August 25, 2016 15:28
Show Gist options
  • Save masaeedu/260ce5e0d982c3653465a9323c9644fa to your computer and use it in GitHub Desktop.
Save masaeedu/260ce5e0d982c3653465a9323c9644fa to your computer and use it in GitHub Desktop.
Flattening function for arbitrarily nested arrays in TypeScript 2.1
// 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
{
"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