Created
November 24, 2019 19:21
-
-
Save Marian0/0a62b502111b4bbf8b3940717ae61cbf to your computer and use it in GitHub Desktop.
Code challenge for Theorem job application
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
/** | |
* This function takes a multidimensional array and return a flat array by running recursively | |
* @param arr | |
* @returns {Array} | |
*/ | |
const arr_flatten = (arr) => { | |
//empty accumulator | |
const flat = []; | |
arr.forEach(item => { | |
if (Array.isArray(item)) { | |
//spread + recursion | |
flat.push(...arr_flatten(item)); | |
return; | |
} | |
flat.push(item); | |
}); | |
return flat; | |
}; | |
/** | |
* Auxiliar method for use on test cases | |
* @param array | |
* @param flat | |
* @param i | |
*/ | |
const method_assert = (array, flat, i) => { | |
const testJSON = JSON.stringify(arr_flatten(array)); | |
const flatJSON = JSON.stringify(flat); | |
if (testJSON !== flatJSON) { | |
console.log(testJSON, ' Diff ', flatJSON); | |
console.warn(`TEST ${i} fails`); | |
return; | |
} | |
console.log(`TEST ${i} passes`) | |
}; | |
/** | |
* Run this function to test all the use cases | |
*/ | |
const test = () => { | |
//Multidimensional case | |
method_assert([1, [2, 3, 4], [5, [6, [7, 8]]]], [1, 2, 3, 4, 5, 6, 7, 8], 1); | |
//Multidimensional case with strings | |
method_assert([1, [2, 3, ['a', 'b', ['c']]], [5, [6, [7, 8]]]], [1, 2, 3, 'a', 'b', 'c', 5, 6, 7, 8], 2); | |
//Same array | |
method_assert([1, 2, 3, 4], [1, 2, 3, 4], 3); | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment