Last active
August 6, 2017 23:41
-
-
Save zeusdeux/75b991097839461f50a0 to your computer and use it in GitHub Desktop.
Flatten nested arrays
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
function flatten(arr) { | |
return arr.reduce( | |
(acc, c) => acc.concat(Array.isArray(c) ? flatten(c) : c), | |
[] | |
); | |
} |
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
// to run, execute: node flatten.test.js | |
'use strict'; | |
const assert = require('assert'); | |
const flatten = require('./flatten'); | |
const tests = [ | |
[[1, 2], [1, 2]], | |
[[1, [2]], [1, 2]], | |
[[[1], 2], [1, 2]], | |
[[[[[[[1], 2]]]]], [1, 2]], | |
[[1, 2, 3, [[[[[4], 5]], 6], 7], 8], [1, 2, 3, 4, 5, 6, 7, 8]], | |
[[], []], | |
[[1], [1]], | |
[[[1]], [1]], | |
[[[[[[[[[1]]]]]]]], [1]] | |
]; | |
const passedTests = tests.reduce(function(p, c, i) { | |
try { | |
assert.deepEqual(flatten(c[0]), c[1]); | |
} | |
catch(e) { | |
console.error('Something broke in test %d', i + 1); | |
throw e; | |
} | |
return ++p; | |
}, 0); | |
console.log('%d tests passed', passedTests); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment