Last active
March 25, 2016 19:40
-
-
Save tinkertrain/f8a746a8a08ac0b1e70e 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
import { isArray } from './utils'; | |
export default function flattenArray(arr) { | |
// Use Array.reduce to get our result | |
let flattened = arr.reduce(function(current, item) { | |
// Store a reference to the current item | |
let temp = item; | |
// Check if the item is an array | |
if (isArray(item)) { | |
// If it is an array, then apply the function again (recursively) and store the result in temp | |
temp = flattenArray(item); | |
} | |
// concat temp with the current result | |
return current.concat(temp); | |
}, []); | |
return flattened; | |
} |
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
import test from 'ava'; | |
import { isArray } from './utils'; | |
import flattenArray from './flattenArray'; | |
test(t => { | |
let testPass = [[1,2,[3, [5, 6]]],4]; | |
let testFail = {}; | |
t.true(isArray(testPass)); | |
t.false(isArray(testFail)); | |
}); | |
test(t => { | |
let test = [[1,2,[3, [5, 6]]],4]; | |
let expected = [ 1, 2, 3, 5, 6, 4 ]; | |
let result = flattenArray(test); | |
t.same(result, expected); | |
}); |
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
// Check is something is an Array, use Array.isArray if it's supported, otherwise use instanceOf | |
export function isArray(arr) { | |
return Array.isArray ? Array.isArray(arr) : arr instanceof Array; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment