Skip to content

Instantly share code, notes, and snippets.

@malixsys
Forked from anonymous/flatten.js
Created February 28, 2018 20:13
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 malixsys/ec3e1c780022435a1560c82e430fdf4e to your computer and use it in GitHub Desktop.
Save malixsys/ec3e1c780022435a1560c82e430fdf4e to your computer and use it in GitHub Desktop.
An array flattener
/**
* @param arr the array to flatten
* @param ret used internally, a starting point if passed
* @returns {Array} a flattened array such that `. [[1,2,[3]],4] -> [1,2,3,4]`
* @example
* const flatten = require('./flatten');
* console.warn(flatten([1, [2, [3, [4]], 5]]));
* // [1, 2, 3, 4, 5]
*/
const flatten = (arr, ret = []) => {
let index = -1;
const length = (arr || []).length;
while (++index < length) {
const value = arr[index];
if (Array.isArray(value)) {
flatten(value, ret);
} else {
ret[ret.length] = value;
}
}
return ret;
};
module.exports = flatten;
// to run tests, use `Jest`
const flatten = require('./flatten');
describe('flatten', () => {
it('should flatten empty arrays', () => {
const arr1 = [];
expect(flatten(arr1)).toEqual([]);
});
it('should return empty arrays on invalid values', () => {
expect(flatten(null)).toEqual([]);
expect(flatten(0)).toEqual([]);
});
it('should flatten shallow arrays', () => {
const arr1 = [1, 2, 3];
expect(flatten(arr1)).toEqual([1, 2, 3]);
const arr2 = ['a', 'b'];
expect(flatten(arr2)).toEqual(['a', 'b']);
});
it('should flatten deep arrays', () => {
const arr1 = [1, [2, [3, [4]], 5]];
expect(flatten(arr1)).toEqual([1, 2, 3, 4, 5]);
const arr2 = [[1, 2, [3]], 4];
expect(flatten(arr2)).toEqual([1, 2, 3, 4]);
})
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment