Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

feat(flatten): Implement variable arity for flatten function, add test #18

Merged
merged 1 commit into from
Feb 29, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions src/flatten.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ export default flatten
/**
* Original Source: http://stackoverflow.com/a/15030117/971592
*
* This method will flatten an array given to it.
* This method will flatten arrays given to it.
*
* @param {Array} arr - The array to flatten
* @param {...Array} arrays - The array(s) to flatten
* @return {Array} - The flattened array
*/
function flatten(arr) {
return arr.reduce(function flattenReducer(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten)
function flatten() {
return [].slice.call(arguments).reduce(function flattenReducer(flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten.apply(null, toFlatten) : toFlatten)
}, [])
}

9 changes: 9 additions & 0 deletions test/flatten.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,12 @@ test('flattens an array of arrays', t => {
const actual = flatten(original)
t.same(actual, expected)
})

test('flattens multiple arrays', t => {
const original1 = [[1, 2], 3, [4, 5]]
const original2 = ['A', 'b', ['C', ['d', 'E']]]
const original3 = [true, false, true, false]
const expected = [1, 2, 3, 4, 5, 'A', 'b', 'C', 'd', 'E', true, false, true, false]
const actual = flatten(original1, original2, original3)
t.same(actual, expected)
})