Created
March 12, 2018 19:59
-
-
Save JasonGhent/901260c058bf1e79d0f7448270f4765a to your computer and use it in GitHub Desktop.
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
/* 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