Created
January 4, 2017 05:05
-
-
Save theadam/e5d6089c9f049a40757a68dd108d51ba to your computer and use it in GitHub Desktop.
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
// Try out by visiting: https://esnextb.in/?gist=e98c7a5295d3e940114ee87b7c273fe2 | |
/* | |
* Recursively flattens each item in the array. | |
*/ | |
function flatten(array) { | |
if (array.length === 0) return array; | |
const [head, ...tail] = array; | |
if (Array.isArray(head)) return flatten(head).concat(flatten(tail)); | |
// If the head is a single item, it just becomes the head of the result. | |
return [head].concat(flatten(tail)); | |
} | |
// TESTS | |
import test from 'tape'; | |
import tapeDom from 'tape-dom' | |
// Show results in the DOM; | |
tapeDom(test); | |
test('empty array', function (t) { | |
t.deepEqual( | |
[], | |
flatten([]), | |
'an empty array should equal a flattened empty array', | |
); | |
t.end(); | |
}); | |
test('already flat array', function (t) { | |
t.deepEqual( | |
flatten([1, 2, 3]), | |
[1, 2, 3], | |
'a flat array should be the same after being flattened', | |
); | |
t.end(); | |
}); | |
test('nested array', function (t) { | |
t.deepEqual( | |
flatten([[[1], [[2, [3]]], 4, [[[5]]]]]), | |
[1, 2, 3, 4, 5], | |
'a nested array should be flattened', | |
); | |
t.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment