Skip to content

Instantly share code, notes, and snippets.

@erineland
Last active June 4, 2019 12:47
Show Gist options
  • Save erineland/b6e7e5706f02886df7ea316124f56957 to your computer and use it in GitHub Desktop.
Save erineland/b6e7e5706f02886df7ea316124f56957 to your computer and use it in GitHub Desktop.
A small tool/exercise for flattening arrays

For this code exercise I went with a simple recursive solution to drill down into each array element, compiling a master array of the individual elements, aiming for elegant code which is readable and functional and ready to ship as it has tests and was written in a TDD manner (as I try to do for all of my tests).

The tests give you examples of how you would run this tool/code for it's desired effect.

E.g.

const ArrayFlattenerTool = require('./array-flattener.js');
const flatArray = ArrayFlattenerTool([1, [1, [2, [3, 4]]], 5]);

console.log(`My new fancy flat array is: ${flatArray});

return flatArray;
const ArrayFlattenerTool = require('./array-flattener-tool.js');
describe('Array flattening tool', () => {
describe('When passed an array with nested arrays', () => {
it('Should throw an error when an array is not passed as a parameter', () => {
try {
const flatArray = ArrayFlattenerTool();
} catch (expectedError) {
expect(expectedError.message).toEqual('Please ensure you pass a valid array to the tool.');
}
})
it('Should return a flattened version of the array', () => {
const flatArray = ArrayFlattenerTool([1, [1, 2], 3]);
expect(flatArray).toEqual([1, 1, 2, 3]);
});
it('Should flatten a doubly nested array', () => {
const flatArray = ArrayFlattenerTool([1, [1, [2, 3]], 4]);
expect(flatArray).toEqual([1, 1, 2, 3, 4]);
})
it('Should flatten a triple nested array!', () => {
const flatArray = ArrayFlattenerTool([1, [1, [2, [3, 4]]], 5]);
expect(flatArray).toEqual([1, 1, 2, 3, 4, 5]);
})
})
});
const flattenArray = (arrayToFlatten, newFlatArray) => {
if (arrayToFlatten.toString().length == 1) {
newFlatArray.push(arrayToFlatten);
} else {
arrayToFlatten.forEach(arrayElement => {
flattenArray(arrayElement, newFlatArray);
});
}
}
module.exports = arrayToFlatten => {
if (!arrayToFlatten) {
throw new Error('Please ensure you pass a valid array to the tool.');
}
const flatArray = [];
flattenArray(arrayToFlatten, flatArray);
return flatArray;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment