Last active
September 6, 2016 19:12
-
-
Save alejandroiglesias/24ce42d4c55ded3a517a2f8dd4c4617b to your computer and use it in GitHub Desktop.
Recursively flattens arbitrarily nested arrays.
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
/** | |
* Recursively flattens arbitrarily nested arrays. | |
* | |
* @param {Array} array The array to flatten. | |
* @param {Array} [result=[]] The initial result value. | |
* @returns {Array} Returns the new flattened array. | |
*/ | |
function flattenArray(array, result = []) { | |
if (!Array.isArray(array)) throw new TypeError('Called on non-array.'); | |
array.forEach(item => { | |
if (Array.isArray(item)) { | |
// Recursively flatten array. | |
flattenArray(item, result); | |
return; | |
} | |
result.push(item); | |
}); | |
return result; | |
} | |
export default flattenArray; |
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 flattenArray from '../../src/flatten-array'; | |
describe('flattenArray', () => { | |
it('it should flatten simple nesting', () => { | |
const nestedArray = [1, 2, 3, [4]]; | |
const flatArray = flattenArray(nestedArray); | |
expect(flatArray).to.be.an('array'); | |
expect(flatArray).to.deep.equal([1, 2, 3, 4]); | |
}); | |
it('it should flatten complex nesting', () => { | |
const nestedArray = [[1,2,[3]],4]; | |
const flatArray = flattenArray(nestedArray); | |
expect(flatArray).to.be.an('array'); | |
expect(flatArray).to.deep.equal([1, 2, 3, 4]); | |
}); | |
it('it should throw if passing a non array', () => { | |
expect(flattenArray).to.throw(TypeError); | |
expect(flattenArray.bind(null, 123)).to.throw(TypeError); | |
expect(flattenArray.bind(null, [1, 2, 3])).not.to.throw(TypeError); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment