Skip to content

Instantly share code, notes, and snippets.

@collinsrj
Created May 10, 2017 22:38
Show Gist options
  • Save collinsrj/afaebf6b7b5ea2e86b4ca4add27580ac to your computer and use it in GitHub Desktop.
Save collinsrj/afaebf6b7b5ea2e86b4ca4add27580ac to your computer and use it in GitHub Desktop.
A simple JavaScript (ES6) function to flatten a nested integer array.
/**
* Flattens an integer array. The function should handle deeply nested arrays
* without issue using an ES6 interpretter which supports Tail Call
* Optimisation.
*
* @returns {Array} a flattened Integer array
*/
const flattenIntArray = array => array
.filter(item => {
if (Number.isInteger(item) || Array.isArray(item)) {
return true
} else {
throw new TypeError("Invalid type in the array. Expected an Integer or an Array.");
}
})
.reduce(
(flattenedArray, item) => flattenedArray.concat(
Array.isArray(item) ? flattenIntArray(item) : item
), []
);
describe("Flatten Array", function(){
it("should flatten nested arrays", function(){
const test = [[[[[1]]]]];
expect(flattenIntArray(test)).toEqual([1]);
});
it("should handle an empty array", function(){
const test = [];
expect(flattenIntArray(test)).toEqual([]);
});
it("should handle nested empty arrays", function(){
const test = [[[],[]]];
expect(flattenIntArray(test)).toEqual([]);
});
it("should handle mixed arrays", function(){
const test = [[1,2,[3]],4];
expect(flattenIntArray(test)).toEqual([1,2,3,4]);
});
it("should handle a flat array", function(){
const test = [1,2,3,4];
expect(flattenIntArray(test)).toEqual([1,2,3,4]);
});
it("should throw a TypeError for nulls in the array", function(){
const testCall = function() {
const test = [1,2,3,4,null];
flattenIntArray(test)
}
expect(testCall).toThrowError(TypeError);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment