Last active
December 7, 2019 20:41
-
-
Save chaucerbao/ee1a07a18da4d141ff0fd7950ab32cc9 to your computer and use it in GitHub Desktop.
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
// Two files (the helper function and its associated tests) have been | |
// concatenated here for the sake of fitting into one Gist. | |
// File: flatten-array.ts | |
// ---------------------- | |
// Type definitions | |
type Nested<T> = Array<T | Nested<T>> | |
// Flattens an array by recursively iterating through items of the | |
// (nested) array, returning the values at the leaf nodes. | |
const flattenArray = (arr: Nested<number>) => | |
arr.reduce<Array<number>>( | |
(flat, value) => | |
flat.concat(Array.isArray(value) ? flattenArray(value) : value), | |
[] | |
) | |
// Exports | |
export { flattenArray } | |
// File: flatten-array.test.ts | |
// --------------------------- | |
// Dependencies | |
import * as assert from 'assert' | |
import { flattenArray } from './flattenArray' | |
// Makeshift test suite | |
try { | |
// Tests | |
assert.deepEqual(flattenArray([]), [], 'Empty array') | |
assert.deepEqual(flattenArray([[], [[], [[], []]]]), [], 'Empty nested array') | |
assert.deepEqual(flattenArray([1, 2, 3, 4]), [1, 2, 3, 4], 'Identity') | |
assert.deepEqual(flattenArray([[1, 2, [3]], 4]), [1, 2, 3, 4], 'Nested array') | |
console.log('Tests passed!') | |
} catch (err) { | |
// Assertion error logging | |
if (err instanceof assert.AssertionError) { | |
const { message, expected, actual } = err | |
console.error( | |
`Test: ${message}\nExpected: ${JSON.stringify( | |
expected | |
)}\nActual: ${JSON.stringify(actual)}` | |
) | |
} else { | |
console.error(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment