Skip to content

Instantly share code, notes, and snippets.

@JasonGhent
Created March 12, 2018 19:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JasonGhent/901260c058bf1e79d0f7448270f4765a to your computer and use it in GitHub Desktop.
Save JasonGhent/901260c058bf1e79d0f7448270f4765a to your computer and use it in GitHub Desktop.
/* flatten an array of integers
* @param arr {Array} - An array of integers to flatten
* @return {Array} - A flattened array of integers
*/
function flatten(arr) {
return arr.reduce((res, _arr) => {
// typecast to array if not already (for next step)
// otherwise, ensure provided array is flat
_arr = Array.isArray(_arr) ? flatten(_arr) : [_arr];
// use push (instead of concat) for memory conservation
for (var i = 0; i < _arr.length; i++) {
res.push(_arr[i]);
}
return res;
}, []);
}
// quick assertion [turbo naive approach]
function flatEqualityCheck(a, b) {
return JSON.stringify(a) === JSON.stringify(b) ? 'PASS' : 'FAIL';
}
const tests = [
{ input: [[1,2,[3]],4], expect: [1,2,3,4] },
{ input: [[1,2,[3],[[]]],4], expect: [1,2,3,4] },
{ input: [[1,2,[3],[['b']]],4], expect: [1,2,3,'b',4] }
];
tests.forEach(test => {
const { input, expect } = test;
const result = flatten(input);
const equality = flatEqualityCheck(result, expect).toString().toUpperCase();
console.log(equality, ':::', expect, '\t<===', input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment