Last active
November 14, 2017 15:33
-
-
Save epzee/e4aa9dfb411fb9a9aea3d97b30a5e28a to your computer and use it in GitHub Desktop.
citrusbyte - flatten // tested on https://repl.it/languages/jest
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
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; |
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
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