Created
March 7, 2017 03:20
-
-
Save gaastonsr/756f0273a35ce6bbfca8d5e6d21e2c38 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
const assert = require('assert'); | |
function flattenArray(array) { | |
return array.reduce((acc, current) => { | |
if (Array.isArray(current)) { | |
return acc.concat(flattenArray(current)); | |
} | |
return acc.concat([current]); | |
}, []); | |
} | |
function emptyArrayTest() { | |
const test = []; | |
const result = flattenArray(test); | |
const expected = []; | |
assert.deepEqual(result, expected); | |
} | |
emptyArrayTest(); | |
function noNestingTest() { | |
const test = [1, 2, 3]; | |
const result = flattenArray(test); | |
const expected = [1, 2, 3]; | |
assert.deepEqual(result, expected); | |
} | |
noNestingTest(); | |
function deeplyNestedTest() { | |
const test = [[1, [2, [[3, 4], [5]]], [6]]]; | |
const result = flattenArray(test); | |
const expected = [1, 2, 3, 4, 5, 6]; | |
assert.deepEqual(result, expected); | |
} | |
deeplyNestedTest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment