Created
January 5, 2018 18:51
-
-
Save jjant/37fb29edec20f52240915b3816147cfa to your computer and use it in GitHub Desktop.
Simple Array flatten implementation in js
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
// Takes an array with possible nested arrays, and returns a **new** flat array. | |
const flatten = array => | |
array.reduce( | |
(flattened, elem) => | |
flattened.concat(Array.isArray(elem) ? flatten(elem) : elem), | |
[] | |
); | |
// From here on below we have only test utilities | |
const test = (testedFunc, input, expectedOutput, comparator) => { | |
const output = testedFunc(input); | |
const testSuccess = comparator(output, expectedOutput); | |
if (!testSuccess) | |
throw new Error(`Test unsuccessful, expected ${JSON.stringify(expectedOutput)}, got ${JSON.stringify(output)}`); | |
return true; | |
}; | |
// Shallow comparison between arrays. | |
const arrayEquals = (array1, array2) => | |
array1.length === array2.length && | |
array1.every((elem, index) => elem === array2[index]); | |
const runTests = () => { | |
try { | |
// Returns equal array on flat arrays | |
test(flatten, [1, 2, 3], [1, 2, 3], arrayEquals); | |
// Flattens array with a singleton array | |
test(flatten, [1, 2, [3]], [1, 2, 3], arrayEquals); | |
// Flattens array with nested array with multiple values | |
test(flatten, [1, [2, 3]], [1, 2, 3], arrayEquals); | |
// Works on edge cases | |
test(flatten, [[]], [], arrayEquals); | |
test(flatten, [], [], arrayEquals); | |
test(flatten, [[], []], [], arrayEquals); | |
test(flatten, [[[]]], [], arrayEquals); | |
} catch (error) { | |
console.log(error); | |
} | |
}; | |
runTests(); // OK |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment