Skip to content

Instantly share code, notes, and snippets.

@allupaku
Created December 26, 2016 06:27
Show Gist options
  • Save allupaku/72bee3ac36a46a375eaaeddae92445c6 to your computer and use it in GitHub Desktop.
Save allupaku/72bee3ac36a46a375eaaeddae92445c6 to your computer and use it in GitHub Desktop.
/**
* Flatten an Array of Integers
*
* @param {Array} integers_array - Array of Numbers
* @return {Array} - Array of Numbers , flattened
*
*/
function flatten(integers_array) {
all_results = [];
if (integers_array && integers_array instanceof Array && integers_array.length > 0) {
integers_array.forEach(function(value) {
if (typeof value === 'number') {
all_results.push(value);
} else if (value instanceof Array && value.length > 0) {
all_results = all_results.concat(flatten(value));
}
});
}
return all_results;
}
/**
* This is a utility function to pring the array under test.
*/
function print_array_as_string(integers_array) {
all_results = "[";
if (integers_array && integers_array instanceof Array && integers_array.length > 0) {
integers_array.forEach(function(value) {
if (!(value instanceof Array)) {
all_results += ((all_results.length > 1 || value === undefined) ? "," : "") + value;
} else if (value instanceof Array) {
all_results += ((all_results.length > 1) ? "," : "") + "[" + flatten(value) + "] ";
}
});
}
return all_results + "]";
}
/**
* This is a method to test the array passed in by printing both the forms.
*/
function test_flatten_with(test_arr) {
console.log(print_array_as_string(test_arr) + " flattened array : ", print_array_as_string(flatten(test_arr)));
}
/**
*
* This is a method used to run all the tests in this function.
*/
function test_suite_flatten() {
test_flatten_with([, , , 1, 2, 3, [4, 5]]);
test_flatten_with([[1, 2], 3, [4, 5]]);
test_flatten_with([[1, 2],[[3]],[4, 5]]);
test_flatten_with([[],[[3]],[5]]);
test_flatten_with([[1],['a']]);
test_flatten_with([[1],[2, 3, 4]]);
test_flatten_with([[1],[[2, [[3]]],[4]]]);
test_flatten_with([[1],[[2, [[3]]],[undefined]]]);
test_flatten_with(undefined);
}
test_suite_flatten();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment