Skip to content

Instantly share code, notes, and snippets.

@one-more
Created December 12, 2019 00:49
Show Gist options
  • Save one-more/8c6cdb4dab8002fc3c885f5a71ce17c4 to your computer and use it in GitHub Desktop.
Save one-more/8c6cdb4dab8002fc3c885f5a71ce17c4 to your computer and use it in GitHub Desktop.
flatten array
interface NestedArray<T> extends Array<T | NestedArray<T>> { }
function flatten(arr: NestedArray<number>) {
return arr.reduce((acc: number[], el) => {
if (Array.isArray(el)) {
return acc.concat(flatten(el))
}
return acc.concat(el)
}, [])
}
function assertEqual(arr1: number[], arr2: number[]) {
if (arr1.length !== arr2.length) {
throw new Error("arrays length differ")
}
arr1.forEach((el, index) => {
if (el !== arr2[index]) {
throw new Error(`
array elements are not equal: arr1[${index}] == ${el},
arr2[${index}] == ${arr2[index]},
${el} !== ${arr2[index]}
`)
}
})
}
function assertThrow(fn: Function, ...args: NestedArray<number>) {
const NotThrownError = "expected function to throw"
try {
fn(...args)
throw new Error(NotThrownError)
} catch(e) {
if (e.message == NotThrownError) {
throw e
}
}
}
assertEqual(
flatten([]),
[]
)
assertEqual(
flatten([1]),
[1]
)
assertEqual(
flatten([1, [2]]),
[1, 2]
)
assertEqual(
flatten([[1,2,[3, [5, [6, [7], [8, [9]]]]]],4]),
[1, 2, 3, 5, 6, 7, 8, 9, 4]
)
assertThrow(
assertEqual,
flatten([1, [2]]),
[1, [2]],
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment