Last active
August 4, 2016 22:17
-
-
Save timurridjanovic/83218342c5e4a4536693d9c01f268a9c to your computer and use it in GitHub Desktop.
Flatten an array
This file contains 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
function flatten(arr) { | |
if (!Array.isArray(arr)) throw new Error('flatten takes an array as a parameter'); | |
return arr.reduce(function(newArr, el) { | |
if (Array.isArray(el)) return flatten(newArr.concat(el)); | |
return newArr.concat(el); | |
}, []); | |
} | |
//uses jasmine as a testing framework | |
describe('Flattening an array', function() { | |
it('should flatten nested array of integers to an array of integers', function() { | |
var arr = [1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[10, 11, [12, 13]]]]], 14]; | |
expect(flatten(arr)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]); | |
}); | |
it('should flatten nested array of generic types to an array of generic types', function() { | |
var arr = [1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[{name: 'hello'}, 'foo', [12, 13]]]]], 14]; | |
expect(flatten(arr)).toEqual([1, 2, [3, 4], [[[5], [6, 7], 8], [9, [[{name: 'hello'}, 'foo', [12, 13]]]]], 14]); | |
}); | |
it('should return empty array', function() { | |
expect(flatten([])).toEqual([]); | |
}); | |
it('should throw an error', function() { | |
expect(function() { flatten({}); }).toThrow(new Error('flatten takes an array as a parameter')); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment