Skip to content

Instantly share code, notes, and snippets.

@hacknlove
Created September 16, 2019 10:23
Show Gist options
  • Save hacknlove/5f66a434f0b4a3c75d7a45f988241050 to your computer and use it in GitHub Desktop.
Save hacknlove/5f66a434f0b4a3c75d7a45f988241050 to your computer and use it in GitHub Desktop.
flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4]
/**
* flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
* @param {[number]} from array to be flatternd
* @param {[number]} [to] array where integers are placed. Defaults to [], and it is used only for recursion.
* @return {[number]} flattern array
*/
function flatten (from, to = []) {
from.forEach(value => {
if (Array.isArray(value)) {
return flatten(value, to)
}
to.push(value)
})
return to
}
exports.flatten = flatten
// jest
const { flatten } = require('./flatten')
test('it returns a new array', () => {
const from = [1, 2, 3, 4]
const to = flatten(from)
expect(to).not.toBe(from)
})
test('origin array is not modified', () => {
const from = [1, 2, 3, 4, [[5, 6, 7], 8]]
flatten(from)
expect(from).toEqual([1, 2, 3, 4, [[5, 6, 7], 8]])
})
test('the array returned is flatten', () => {
const to = flatten([1, 2, 3, 4, [[5, 6, 7], 8]])
expect(to).toEqual([1, 2, 3, 4, 5, 6, 7, 8])
})
test('it does not crash with an empy array', () => {
expect(() => flatten([])).not.toThrow()
})
test('it has no problems with deep empty arrays', () => {
const to = flatten([1, 2, [], 3, 4, [[], 5]])
expect(to).toEqual([1, 2, 3, 4, 5])
})
test('It flattern a very tough one', () => {
const to = flatten([[[]], [[[1]]], [[2, [], 3]], [[4, [[], 5], [[[[],[[]]]]]]], [[[[[[[[[[6]]]]]]]]]]])
expect(to).toEqual([1, 2, 3, 4, 5, 6])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment