Created
September 30, 2016 10:28
-
-
Save shanecav/1083f479b3223c7be3aabea5ef3f3b97 to your computer and use it in GitHub Desktop.
A function that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers
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
// recursively flatten arbitrarily nested array(s) of integers | |
const flatten = (arr) => { | |
// Reduce nested array(s) into a flat array (starting with empty array) | |
return arr.reduce((prev, cur) => { | |
if (Array.isArray(cur)) { | |
// if it's an array, concat its flattened result | |
return prev.concat(flatten(cur)) | |
} | |
if (Number.isInteger(cur)) { | |
// if it's an integer, concat the value | |
return prev.concat(cur) | |
} | |
// throw if it's not an array or integer | |
throw new TypeError('each value of the array must be either an integer or another array') | |
}, []) | |
} | |
export default flatten |
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
import { expect } from 'chai' | |
import { describe, it } from 'mocha' | |
import flatten from './flatten' | |
describe('flatten', () => { | |
it('should flatten deeply nested arrays', () => { | |
expect(flatten([[1,2,[3]],4])).to.deep.equal([1, 2, 3, 4]) | |
expect(flatten([1, [2, 7], 3, [4, 5, 6, [1, 2, [3, [4]]]]])).to.deep.equal([1, 2, 7, 3, 4, 5, 6, 1, 2, 3, 4]) | |
}) | |
it('should not change flat arrays', () => { | |
expect(flatten([1, 2, 3, 4])).to.deep.equal([1, 2, 3, 4]) | |
expect(flatten([4])).to.deep.equal([4]) | |
expect(flatten([])).to.deep.equal([]) | |
}) | |
it('should throw if any array value is not an integer or another array', () => { | |
expect(() => flatten(['not an integer'])).to.throw(TypeError) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment