Skip to content

Instantly share code, notes, and snippets.

@iyobo
Last active January 18, 2018 01:13
Show Gist options
  • Save iyobo/b5078ca37f1cf9ffb89e22e110662218 to your computer and use it in GitHub Desktop.
Save iyobo/b5078ca37f1cf9ffb89e22e110662218 to your computer and use it in GitHub Desktop.
/**
* Takes an array or a single number and flattens it into a result array.
*
* @param input: Array|any
* @param resultArray: Array|null - optional. array into which all inputs get flattened into. Uses an empty array if none provided.
*/
const flatten = function (input, resultArray = []) {
if (!Array.isArray(resultArray))
throw new Error('ResultArray must be an array')
if (Array.isArray(input)) {
for (const item of input) {
flatten(item, resultArray)
}
}
else if (input) {
resultArray.push(input)
}
return resultArray;
}
exports.flatten = flatten;
/**
To run this test, you may put it in the same directory of flatten.js and then use a test runner like mocha. i.e
- npm i -g mocha
- mocha flatten.test.js
**/
const assert = require('assert');
const flatten = require('./flatten').flatten;
describe('flatten', function () {
it('flattens an array', function (done) {
const input = [[1, 2, [3]], 4];
const expected = [1, 2, 3, 4];
const result = flatten(input);
assert.deepStrictEqual(result, expected);
done();
});
it('flattens very deep arrays', function (done) {
const input = [[1, 2, [3]], [[[[[[5]], 4]]]], 7];
const expected = [1, 2, 3, 5, 4, 7];
const result = flatten(input);
assert.deepStrictEqual(result, expected);
done();
});
it('flattens already-flattened Array', function (done) {
const input = [1, 2, 3, 9, 3];
const expected = [1, 2, 3, 9, 3];
const result = flatten(input);
assert.deepStrictEqual(result, expected);
done();
});
it('Returns item wrapped in array if singular item', function (done) {
const input = 9;
const expected = [9];
const result = flatten(input);
assert.deepStrictEqual(result, expected);
done();
});
it('Returns an empty Array if nothing to flatten', function (done) {
const input = null;
const expected = [];
const result = flatten(input);
assert.deepStrictEqual(result, expected);
done();
});
it('Appends to ResultArray', function (done) {
const input = [1, 2, 3];
const expected = [5, 6, 7, 1, 2, 3];
const result = flatten(input, [5, 6, 7]);
assert.deepStrictEqual(result, expected);
done();
});
it('only accepts an array for ResultArray Param', function (done) {
const input = [1, 2, 3];
try {
const result = flatten(input, null);
assert.fail('An error should throw as ResultArray param was not an array');
} catch (err) {
done();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment