Skip to content

Instantly share code, notes, and snippets.

@fracasula
Last active May 9, 2019 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fracasula/6a6af8e19150fee5753be297e8fb5702 to your computer and use it in GitHub Desktop.
Save fracasula/6a6af8e19150fee5753be297e8fb5702 to your computer and use it in GitHub Desktop.
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