Skip to content

Instantly share code, notes, and snippets.

@jbruni
Created October 5, 2016 19:16
Show Gist options
  • Save jbruni/3dacb9ebd0e108add8e59d9768a08bc2 to your computer and use it in GitHub Desktop.
Save jbruni/3dacb9ebd0e108add8e59d9768a08bc2 to your computer and use it in GitHub Desktop.
J Bruni's "getFlattenedIntegers"
/*** Running CodePen available at http://codepen.io/anon/pen/VKyAVw ***/
/**
* Flatten an array of arbitrarily
* nested arrays of integers into
* a flat array of integers.
*/
function getFlattenedIntegers(integers) {
var result = []
function pushInt(value) {
if (typeof value === "number") {
if (value === parseInt(value)) {
// Push into results if value is an integer
result.push(value)
}
}
else if (isArray(value)) {
// Loop through all values if value is an array
value.forEach(function(item) {
pushInt(item)
})
}
}
pushInt(integers)
return result
}
/**
* Check if value looks like an array
*/
function isArray(value) {
if (typeof value === 'undefined') return false
if (value === null) return false
return ((typeof value.length === 'number')
&& (typeof value.forEach === 'function'))
}
/*** Tests ***/
/**
* Expected inputs + outputs to test against.
*/
var tests = [
{
input: [[1,2,[3]],4],
output: [1,2,3,4]
}, {
input: [[9,[8,7,6],5],4,[3,2],[1]],
output: [9,8,7,6,5,4,3,2,1]
}, {
input: [5],
output: [5]
}, {
input: 5,
output: [5] // auto-converts to array (assumption)
}, {
input: '5',
output: [] // not an integer
}, {
input: [[[[1], 2], 3],null,5,'hi',[7,[7.5],8],NaN,Infinity],
output: [1,2,3,5,7,8] // ignores non-integer values
}
]
/**
* Compares result with expected output
*/
function checkResult(result, expected) {
var max = result.length;
if (max !== expected.length) {
return false
}
for (var i = 0; i < max; i++) {
if (result[i] !== expected[i]) {
return false
}
}
return true
}
/**
* Run "test suite" outputting the results
*/
document.write('<pre>')
tests.forEach(function(test){
var result = getFlattenedIntegers(test.input)
var passed = checkResult(result, test.output)
document.write('input: ' + test.input + '\n')
document.write('output: ' + result + '\n')
document.write('expected: ' + test.output + '\n')
document.write('result: <b>' + (passed ? 'passed' : 'failed') + '</b>\n\n')
})
document.write('</pre>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment