Last active
March 21, 2019 12:16
-
-
Save nateq314/ab32067f3e4c952716629ac4b5a516db to your computer and use it in GitHub Desktop.
non-mutating flatten()
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
/** | |
* 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[]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment