Last active
October 15, 2018 16:27
-
-
Save Jero786/8189f6f28f99a209c14d73760bc19495 to your computer and use it in GitHub Desktop.
A simple flatten array
This file contains 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
/** | |
* Given a array of array values, will return a new instance with a flatten array. | |
* | |
* @param {Array} The array which will be flatten | |
* @param {Array} The new flatten array (private) | |
* @param {number} A position index that use to traverse given array. (private) | |
* @return {Array} The new array flatten | |
* @public | |
*/ | |
function flatten(numbers, result, index) { | |
// init | |
if (result === undefined) { | |
result = []; | |
index = 0; | |
return flatten(numbers || [], result, index); | |
} | |
// end | |
if (!numbers || numbers.length === index) { | |
return result; | |
} | |
// action | |
let currentNode = numbers[index]; | |
if (Array.isArray(currentNode)) { | |
currentNode = flatten(currentNode, [], 0); | |
result = result.concat(currentNode); | |
} else { | |
result.push(currentNode); | |
} | |
return flatten(numbers, result, ++index); | |
} | |
describe("Flatten array", () => { | |
it("should flatten array with single nested level", () => { | |
const SUT = [[1, 2, 3], 4]; | |
const result = flatten(SUT); | |
expect(result[0]).toEqual(1); | |
expect(result[1]).toEqual(2); | |
expect(result[2]).toEqual(3); | |
expect(result[3]).toEqual(4); | |
expect(result.length).toEqual(4); | |
}); | |
it("should flatten multi-level nested array with single item", () => { | |
const SUT = [[[3]]]; | |
const result = flatten(SUT); | |
expect(result[0]).toEqual(3); | |
expect(result.length).toEqual(1); | |
}); | |
it("should have tolerance to non-array", () => { | |
const result = flatten(); | |
expect(result.length).toEqual(0); | |
}); | |
it("should have tolerance to an empty array", () => { | |
const SUT = []; | |
const result = flatten(SUT); | |
expect(result.length).toEqual(0); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment