Skip to content

Instantly share code, notes, and snippets.

@bcawrse
Last active August 21, 2019 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bcawrse/04a17dae7f534de1da214a1c05614305 to your computer and use it in GitHub Desktop.
Save bcawrse/04a17dae7f534de1da214a1c05614305 to your computer and use it in GitHub Desktop.
Flatten example written in Node with jest tests
/**
* Flattens provided array.
*
* If an array is provided, this function will flatten it.
* EXAMPLE: flatten([[1, 2, [3]], 4]) returns [1, 2, 3, 4].
*
* @throws Throws an exception if provided parameter is not an Array.
* @param {Array} arr Array to flatten.
* @return {array} Flattend Array.
**/
function flatten(arr)
{
// Sanatize input, throw if not an Array.
if (!Array.isArray(arr)) {
throw 'Provided parameter is not an array.';
}
var result = [];
// Run recursive reducer with array and result parameters.
(function reducer(arr, state) {
arr.forEach((item) => {
// Continue reducing if array item is a nested Array.
if (Array.isArray(item)) {
reducer(item, state);
}
// Add array item to result if not an Array.
else {
state.push(item);
}
});
return state;
})(arr, result);
return result;
}
module.exports = flatten;
/**
* Meant to be run with jest. If jest is not part of the project
* you may install it globally to the system with npm i --global jest
**/
const flatten = require('./flatten.js');
describe("Testing Flatten.js", () => {
test('flatten() Throws Exception', () => {
expect(() => { flatten() }).toThrow();
});
test('flatten(undefined) Throws Exception', () => {
expect(() => { flatten(undefined) }).toThrow();
});
test('flatten(5) Throws Exception', () => {
expect(() => { flatten(5) }).toThrow();
});
test('flatten(\'z\') Throws Exception', () => {
expect(() => { flatten('z') }).toThrow();
});
test('flatten([]) = []', () => {
expect(flatten([]))
.toEqual([]);
});
test('flatten([1, 2, [], 4]) = [1, 2, 4]', () => {
expect(flatten([1, 2, [], 4]))
.toEqual([1, 2, 4]);
});
test('flatten([1, 2, 3, 4]) = [1, 2, 3, 4]', () => {
expect(flatten([1, 2, 3, 4]))
.toEqual([1, 2, 3, 4]);
});
test('flatten([[1, 2, [3]], 4]) = [1, 2, 3, 4]', () => {
expect(flatten([[1, 2, [3]], 4]))
.toEqual([1, 2, 3, 4]);
});
test('flatten([1, 2, [1, 2, 3]] = [1, 2, 1, 2, 3]', () => {
expect(flatten([1, 2, [1, 2, 3]]))
.toEqual([1, 2, 1, 2, 3]);
});
test('flatten([1, 2, [1, 2, 3]] != [1, 1, 2, 2, 3]', () => {
expect(flatten([1, 2, [1, 2, 3]]))
.not.toEqual([1, 1, 2, 2, 3]);
});
test('flatten([1, 2, [3, 2, 1, [1, 2, 3, 4, 5], 1, 2, 3], 3, 4, 5]) = [1, 2, 3, 2, 1, 1, 2, 3, 4, 5, 1, 2, 3, 3, 4, 5]', () => {
expect(flatten([1, 2, [3, 2, 1, [1, 2, 3, 4, 5], 1, 2, 3], 3, 4, 5]))
.toEqual([1, 2, 3, 2, 1, 1, 2, 3, 4, 5, 1, 2, 3, 3, 4, 5]);
});
test('flatten([[[1], 2]]) = [1, 2]', () => {
expect(flatten([[[1], 2]]))
.toEqual([1, 2]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment