Created
December 12, 2019 00:49
-
-
Save one-more/8c6cdb4dab8002fc3c885f5a71ce17c4 to your computer and use it in GitHub Desktop.
flatten array
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
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