Skip to content

Instantly share code, notes, and snippets.

@epzee
Last active November 14, 2017 15:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epzee/e4aa9dfb411fb9a9aea3d97b30a5e28a to your computer and use it in GitHub Desktop.
Save epzee/e4aa9dfb411fb9a9aea3d97b30a5e28a to your computer and use it in GitHub Desktop.
citrusbyte - flatten // tested on https://repl.it/languages/jest
const reducer = (result, item) => {
const flattened = Array.isArray(item) ? flatten(item) : item;
return result.concat(flattened);
}
const flatten = (array) => array.reduce(reducer, []);
module.exports = flatten;
const flatten = require('./flatten');
describe('flatten', () => {
it('should not modify flat arrays', () => {
expect(flatten([])).toEqual([]);
expect(flatten([1,2,3])).toEqual([1,2,3]);
});
it('should not mutate existing array', () => {
const originalArray = [1,[2,3],4];
const copy = originalArray.slice(0);
flatten(originalArray);
expect(originalArray).toEqual(copy);
});
it('should flatten nested arrays', () => {
expect(flatten([[3]])).toEqual([3]);
expect(flatten([1,[2,3],4])).toEqual([1,2,3,4]);
});
it('should flatten deeply nested arrays', () => {
expect(flatten([[[[3]]]])).toEqual([3]);
expect(flatten([1,[[2,3]],4,[5,[6,7],8],9])).toEqual([1,2,3,4,5,6,7,8,9]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment