Skip to content

Instantly share code, notes, and snippets.

@generalistcodes
Last active August 8, 2016 05:14
Show Gist options
  • Save generalistcodes/a9f6fc7c54c02b184a4722669311ee44 to your computer and use it in GitHub Desktop.
Save generalistcodes/a9f6fc7c54c02b184a4722669311ee44 to your computer and use it in GitHub Desktop.
Flatten an Array of Arbitrarily nested Arrays of Integers into a Flat Array of Integers: With Unit Test using Jasmine
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine.min.js"></script>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/jasmine-html.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.3.3/boot.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
describe("Flatten an Array of Arbitrarily nested Arrays of Integers into a Flat Array of Integers", function () {
it("Should return an empty array when empty array provided", function () {
expect(Flatter.getFlatten([])).toEqual([]);
});
it("Should return an empty array when undefined value provided", function () {
expect(Flatter.getFlatten(undefined)).toEqual([]);
});
it("Should return a flat array when a flat array is provided", function () {
expect(Flatter.getFlatten([1, 2])).toEqual([1, 2]);
});
it("Should return [1,2,3,4] on [[1,2,[3]],4] provided", function () {
expect(Flatter.getFlatten([[1, 2, [3]], 4])).toEqual([1, 2, 3, 4]);
});
it("Should return [1,4,5,6] on [[1,[4],5,6]] provided", function () {
expect(Flatter.getFlatten([[1, [4], 5, 6]])).toEqual([1, 4, 5, 6]);
});
it("Should return [1] on [[[1]]] provided", function () {
expect(Flatter.getFlatten([[[1]]])).toEqual([1]);
});
});
/**
* 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 {Array} integers_array - Array of Numbers
* @param {Array} flatten_array - Flatten array (for recursive mode) of Numbers
* @return {Array} - Merge/Flatten Array of Numbers
*/
var Flatter = (function () {
var flatten = function (integers_array, flatten_array) {
var flatten_results = flatten_array || [];
if (integers_array && integers_array.length > 0) {
//iterate over the arrays and merge them recursively
integers_array.forEach(function (value) {
if (typeof value === 'number') {
flatten_results.push(value);
} else if (value instanceof Array) {
flatten(value, flatten_results);
}
});
}
return flatten_results; // Return all flatten Array of numbers.
};
return {
getFlatten: flatten
}
})();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment