Skip to content

Instantly share code, notes, and snippets.

@chelorossi
Last active March 15, 2018 04:39
Show Gist options
  • Save chelorossi/432111074dc7819b5037ca1fe7bfc457 to your computer and use it in GitHub Desktop.
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]. )
/**
* 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();
}
//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');
};
@chelorossi
Copy link
Author

Added solution, and some tests. Used a stack, for perfomance pursposes.
I tried recursive solution first but it exceeds stack fast (like in 1E4 arrays length)

Of course we could test more and polish, but I think will suite the purpose of my application.

Kind Regards,
Marcelo

@chelorossi
Copy link
Author

I also tried functional js but I disregard it because of modernJS engines TCO (Tail Call optimization) don't implement it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment