-
-
Save malixsys/ec3e1c780022435a1560c82e430fdf4e to your computer and use it in GitHub Desktop.
An array flattener
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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