Skip to content

Instantly share code, notes, and snippets.

@svschannak
Last active April 13, 2018 10:24
Show Gist options
  • Save svschannak/485135be93ae1b50bd27feb54e730afd to your computer and use it in GitHub Desktop.
Save svschannak/485135be93ae1b50bd27feb54e730afd to your computer and use it in GitHub Desktop.
Array flattener
// You can test it in the browser here: https://codepen.io/svschannak/pen/KoLZvm?editors=0011
// try to avoid using const and arrow functions to declare an function, it will help you while debugging
function flatten_array(originList){
/**
* Flattens an input list with multi levels.
* WORKS only with ES6
* Description. (use period)
* @param {Array[List]} originList Array List to be flattened.
*
* @return {Array[List]} New flattened array list.
*/
let returnList = [];
let currentItem;
// walk through all array elements
while (currentItem = originList.shift()) {
// check if the current item is an array
if (Array.isArray(currentItem)) {
// try to flatten the next list item
const flattenedList = flatten_array(currentItem);
// merge flattened list and current list
returnList = returnList.concat(flattenedList);
} else {
// if current item is not a list, push the item to the return list
returnList.push(currentItem);
}
}
return returnList;
}
const TEST_CASES = [
{ origin: [[1,2,[3]],4], result: [1,2,3,4], shouldNotFail: true},
{ origin: [[1,2,[[3]]],4], result: [1,2,3,4], shouldNotFail: true },
// also check false positives
{ origin: [[1,2,[[3]]],5], result: [1,2,3,4], shouldNotFail: false }
]
function checkIfArraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length){
return false;
}
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
TEST_CASES.forEach((testCase, idx) => {
const flattened_array = flatten_array(testCase['origin']);
const check = checkIfArraysEqual(flattened_array, testCase['result']);
if(check === testCase['shouldNotFail']){
console.log(`TEST for testcase no. ${idx + 1} SUCCESSFUL`);
}else{
console.log(`TEST for testcase no. ${idx + 1} FAILED`);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment