Last active
May 9, 2019 09:30
-
-
Save fracasula/6a6af8e19150fee5753be297e8fb5702 to your computer and use it in GitHub Desktop.
JS Bin// source https://jsbin.com/fayomupale
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
const flattenArray = input => { | |
if (!Array.isArray(input)) { | |
throw new Error("Input must be an array") | |
} | |
let result = [] | |
for (let element of input) { | |
if (Array.isArray(element)) { | |
result = result.concat(flattenArray(element)) | |
} else { | |
result.push(element) | |
} | |
} | |
return result | |
} | |
const scenarios = { | |
one: { | |
input: [[1, 2, [3]], 4], | |
expected: [1, 2, 3, 4], | |
}, | |
two: { | |
input: [1, [2], [], [3, [4, [5, [6, [], []]], 7], 8], 9, [], []], | |
expected: [1, 2, 3, 4, 5, 6, 7, 8, 9], | |
}, | |
three: { | |
input: "ciao", | |
expected: new Error("Input must be an array"), | |
}, | |
} | |
for (const [name, scenario] of Object.entries(scenarios)) { | |
let actual = null | |
try { | |
actual = flattenArray(scenario.input) | |
} catch (e) { | |
actual = e | |
} | |
const jsonActual = JSON.stringify(actual) | |
const jsonExpected = JSON.stringify(scenario.expected) | |
if (jsonActual !== jsonExpected) { | |
console.log( | |
`Scenario ${name} failed, expected ${jsonExpected}, got ${jsonActual} instead.`) | |
} | |
} | |
console.log("Done!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment