Skip to content

Instantly share code, notes, and snippets.

@vpellegrino
Last active December 29, 2019 02:52
Show Gist options
  • Save vpellegrino/4dca7d9d53d7750d129d3aa0e9f6ea08 to your computer and use it in GitHub Desktop.
Save vpellegrino/4dca7d9d53d7750d129d3aa0e9f6ea08 to your computer and use it in GitHub Desktop.
Task: write some code that will flatten an array of arbitrarily nested arrays of integers into a flat array of integers
/**
* production code
*/
const flatten = arr => safeArray(arr).reduce(flatReducer, []);
const safeArray = arr => Array.isArray(arr) ? arr : [];
const flatReducer = (res, elem) => {
if (Array.isArray(elem)) {
return res.concat(flatten(elem));
}
return res.concat(elem);
};
/**
* unit tests
*/
mocha.setup('bdd');
const assert = chai.assert;
describe('given an array, flattening it', () => {
describe('when it is already flat', () => {
it('should produce the original array', function () {
const arr = [1, 2, 3, 4];
assert.deepEqual(flatten(arr), [1, 2, 3, 4]);
});
});
describe('when it has only one level of nesting', () => {
it('should produce an array of integers w/o nested elements', function () {
const arr = [[1, 2, 3], 4];
assert.deepEqual(flatten(arr), [1, 2, 3, 4]);
});
});
describe('when it is deeply nested', () => {
it('should produce an array of integers w/o nested elements', function () {
const arr = [[1, 2, [3]], 4];
assert.deepEqual(flatten(arr), [1, 2, 3, 4]);
});
});
describe('when it is empty', () => {
it('should produce an empty array', function () {
assert.deepEqual(flatten([]), []);
});
});
describe('when it is null or undefined', () => {
it('should produce an empty array', function () {
assert.deepEqual(flatten(null), []);
assert.deepEqual(flatten(undefined), []);
});
});
});
mocha.run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment