Skip to content

Instantly share code, notes, and snippets.

@paulohp
Created October 26, 2018 20:58
Show Gist options
  • Save paulohp/d5d8771fc01537a2d75bc4ab6146cb5d to your computer and use it in GitHub Desktop.
Save paulohp/d5d8771fc01537a2d75bc4ab6146cb5d to your computer and use it in GitHub Desktop.
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));
}
//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