Skip to content

Instantly share code, notes, and snippets.

@draganSm draganSm/flatten.js
Created Feb 1, 2017

Embed
What would you like to do?
/**
* Flattens the giving array recursively
* @param array
* @returns {Array}
*/
export default function flattenArray(array, result = []) {
for (const element of array) {
if (Array.isArray(element)) {
flattenArray(element, result);
}
else {
result.push(element);
}
}
return result;
}
/*
if Array.reduce is allowed I'd use this
const flattenArray2 = array =>
array.reduce((result, element) =>
result.concat(Array.isArray(element) ? flattenArray2(element) : element),
[]);
*/
import range from 'lodash/range';
import flatten from '../flatten';
import chai from 'chai';
chai.should();
describe('Flatten', () => {
it('should support empty array', () => {
flatten([]).should.be.deep.equal([]);
});
it('should flatten array of numbers', () => {
flatten([1, 2, 3]).should.be.deep.equal([1, 2, 3]);
});
it('should flatten array of array', () => {
flatten([[1], [2], [3], [4], [5]]).should.be.deep.equal([1, 2, 3, 4, 5]);
});
it('should flatten nested arrays', () => {
flatten([1, [2], [3, [4, 5]]]).should.be.deep.equal([1, 2, 3, 4, 5]);
});
it('should flatten very deep array', () => {
/*
the flatten method is using recursion so it can't handle extremely deep arrays; "Maximum call stack size exceeded" will be thrown
$ node --v8-options | grep -B0 -A1 stack_size
> --stack_size (default size of stack region v8 is allowed to use (in kBytes))
> type: int default: 984
*/
const array = range(1e3);
const deepArray = array.slice(1).reduce((result, element) => [result, element], [0]);
// [[[[[... [0], 1], 2], ..., 999]
flatten(deepArray).should.be.deep.equal(array);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.