Skip to content

Instantly share code, notes, and snippets.

@gabrielgodoy-zz
Last active December 16, 2016 22:44
Show Gist options
  • Save gabrielgodoy-zz/e7584f88ff0ff8fe93e69d4ba12c6ec3 to your computer and use it in GitHub Desktop.
Save gabrielgodoy-zz/e7584f88ff0ff8fe93e69d4ba12c6ec3 to your computer and use it in GitHub Desktop.
Flat array
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