Created
April 7, 2019 14:43
-
-
Save SaitTalhaNisanci/940947ae353596fff5a1aa53182bf41a to your computer and use it in GitHub Desktop.
Flatten an array of nested elements.
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
// Flattens the given nested elements. | |
function flattenArray(elements) { | |
if (elements === undefined || !Array.isArray(elements)) { | |
throw "Array is expected"; | |
} | |
return elements.reduce((result, current) => { | |
return result.concat(Array.isArray(current) ? flattenArray(current) : current); | |
}, []); | |
} | |
// Checks if two array are equal. | |
function assertArraysEqual(arr1, arr2) { | |
if (arr1.length !== arr2.length) { | |
return false; | |
} | |
for (var i = 0; i < arr1.length; i++) { | |
if (arr1[i] !== arr2[i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function assert(condition, message) { | |
if (!condition) { | |
message = message || "Assertion failed"; | |
if (typeof Error !== "undefined") { | |
throw new Error(message); | |
} | |
throw message; // Fallback | |
} | |
} | |
function testFlattenArray() { | |
assert(assertArraysEqual(flattenArray([2, 2, 3]), flattenArray([[1], 2, 3])) === false); | |
assert(assertArraysEqual(flattenArray([1, 2, 3]), flattenArray([[1], 2, 3])) === true); | |
assert(assertArraysEqual(flattenArray([1, 2, 3]), flattenArray([1, 2, 3])) === true); | |
assert(assertArraysEqual(flattenArray([]), flattenArray([])) === true); | |
assert(assertArraysEqual(flattenArray([1, [2], [3]]), flattenArray([[1], 2, 3])) === true); | |
assert(assertArraysEqual(flattenArray([[[1]], [[2]], 3]), flattenArray([[1], 2, 3])) === true); | |
assert(assertArraysEqual(flattenArray([2, 2]), flattenArray([[1], 2, 3])) === false); | |
assert(assertArraysEqual(flattenArray([2]), flattenArray([1])) === false); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment