Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Return the flattened version of an arbitrarily deep nested array as a new
- * array, keeping the original unchanged. It uses a simple recursive algorithm.
- *
- * Positives: clean, intuitive, doesn't mutate the argument
- * Negatives: 1) probably uses more memory than alternative implementations.
- * 2) recursive, so in theory more limited by system resources than
- * an alternative non-recursive algorithm would be. Unlikely to
- * be a problem in most use cases but if you had an array nested
- * say 1 million levels deep, probably wouldn't want to use this
- * method.
- *
- * @param unflattened
- */
- export default function flatten(unflattened: any[]) {
- try {
- return unflattened.reduce(
- (flattened: any[], currElement: any) =>
- flattened.concat(
- Array.isArray(currElement) ? flatten(currElement) : currElement,
- ),
- [],
- );
- } catch (error) {
- // because Typescript !== foolproof
- return console.error(`Error! ${error.message}`);
- }
- }
- function test(arg: any) {
- console.log(
- `flatten(${JSON.stringify(arg)}) = ${JSON.stringify(flatten(arg))}`,
- );
- }
- export function tests() {
- test([1, [2, 3, [4, 5, 6, [[7], 8], 9, 10]]]);
- test([1, 2, 3, 4]);
- test(2);
- test(('hello' as any) as number[]);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement