Last active
December 16, 2016 22:44
-
-
Save gabrielgodoy-zz/e7584f88ff0ff8fe93e69d4ba12c6ec3 to your computer and use it in GitHub Desktop.
Flat array
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
let someArray = [[1, 2, [3]], 4]; | |
function flatArray(arrayToFlat) { | |
let arrayFlattened = []; | |
if (!Array.isArray(arrayToFlat)) { | |
return 'This is not an object of type Array'; | |
} | |
function flat(arrayToFlat) { | |
arrayToFlat.map((arrayItem, index, arr) => { | |
if (Array.isArray(arrayItem)) { | |
flat(arrayItem); | |
} else { | |
arrayFlattened.push(arrayItem); | |
} | |
; | |
}); | |
return arrayFlattened; | |
} | |
return flat(arrayToFlat); | |
} | |
flatArray(someArray); // [1,2,3,4] | |
// TESTING | |
function it(shouldMessage, testCase) { | |
return { | |
toEqual: (expected) => compareArrays(testCase, expected) ? `"${shouldMessage}" succeded` : `"${shouldMessage}" failed` | |
}; | |
} | |
// This function do not check for equality of literal objects | |
function compareArrays(testCase, expected) { | |
switch (Array.isArray(testCase)) { | |
case true: | |
return testCase.length === expected.length && testCase.every((element, index) => element === expected[index]); | |
break; | |
default: | |
return testCase === expected; | |
} | |
} | |
let initialArray = [[1, 2, [3]], 4], | |
result = [1, 2, 3, 4]; | |
it('Should flat the array with the correct output', flatArray(initialArray)).toEqual([1, 2, 3, 4]); | |
it('Should return error message if parameter not Array', flatArray(1)).toEqual("This is not an object of type Array"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment