Created
October 26, 2018 20:58
-
-
Save paulohp/d5d8771fc01537a2d75bc4ab6146cb5d to your computer and use it in GitHub Desktop.
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
module.exports = function flatten(nestedArrays) { | |
if (!Array.isArray(nestedArrays)) | |
throw new Error("flatten() called with non-array"); | |
function* f(nestedArrays) { | |
for (let element of nestedArrays) | |
if (Array.isArray(element)) yield* f(element); | |
else yield element; | |
} | |
return Array.from(f(nestedArrays)); | |
} |
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
//tests written with Jest | |
const flatten = require('./') | |
describe('Flatten', () => { | |
const nonArray = {a: {b:{}}} | |
const stringArray = ['a', 'b', ['c', 'd']] | |
const intArray = [1, 2, [3, 4]] | |
const deepIntArray = [1,2,[1,2,[1,2,['a', 'b']]]] | |
it('should fail if flatten receives non-array', () => { | |
expect(() => flatten(nonArray)).toThrowError('flatten() called with non-array') | |
}) | |
it('should flatten array of strings', () => { | |
expect(flatten(stringArray)).toEqual(['a', 'b', 'c', 'd']) | |
}) | |
it('should flatten array of integers', () => { | |
expect(flatten(intArray)).toEqual([1, 2, 3, 4]) | |
}) | |
it('should flatten array of deep integers', () => { | |
expect(flatten(deepIntArray)).toEqual([1, 2, 1, 2, 1, 2, 'a', 'b']) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment