Last active
March 15, 2018 04:39
-
-
Save chelorossi/432111074dc7819b5037ca1fe7bfc457 to your computer and use it in GitHub Desktop.
SOLUTION - (Write some code, that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]. )
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
| /** | |
| * flatten() returns a flattened array | |
| * based on the passed-in nested integer array uiarray | |
| * must preprocess (minify and uglify) with a tool like webpack to deploy in production | |
| * Tested in Chrome latest (I would do some more testing) | |
| */ | |
| const flatten = function flattenIntegersArray(uiarray) { | |
| //console.assert(Array.isArray(uiarray), 'is not an Array param uiarray'); | |
| var stack = uiarray.slice(0); | |
| var res = []; | |
| while (stack.length > 0) { | |
| var elem = stack.pop(); | |
| if (elem.length === 0) { | |
| continue; | |
| } | |
| if (Number.isInteger(elem)) { | |
| res.push(elem); | |
| } else { | |
| for (var i=0; i < elem.length; i++) { | |
| stack.push(elem[i]); | |
| } | |
| } | |
| } | |
| return res.reverse(); | |
| } |
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
| //USE: just invoke test_flattener() | |
| const test_flattener = () => { | |
| const compare = (a1, a2) => a1.length==a2.length && a1.every((v,i)=> v === a2[i]); | |
| const empty_array = []; | |
| console.assert(compare(flatten(empty_array), []), 'empty_array'); | |
| const empties_array = [[[[[[[[]]]]]]]]; | |
| console.assert(compare(flatten(empties_array), []), 'empties_array'); | |
| const unidimensional_array = [1,2,3,3]; | |
| console.assert(compare(flatten(unidimensional_array), [1,2,3,3]), 'unidimensional_array'); | |
| const example_array = [[1,2,[3]],4]; | |
| console.assert(compare(flatten(example_array), [1,2,3,4]), 'example_array'); | |
| const complex_array = [1,[2,3,[4,[5,[[6]]]]]]; | |
| console.assert(compare(flatten(complex_array), [1,2,3,4,5,6]), 'complex_array'); | |
| const bigFatArray = []; | |
| for (var i=0; i<=1.5E7; i++) { | |
| bigFatArray.push(i) | |
| } | |
| console.assert(compare(flatten(bigFatArray), bigFatArray), 'bigFatArray'); | |
| console.log('if no errors before everything went fine'); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I also tried functional js but I disregard it because of modernJS engines TCO (Tail Call optimization) don't implement it.