snippetjavascriptMinor
Convert three functions into a single function
Viewed 0 times
threeconvertintofunctionsinglefunctions
Problem
Is it possible to combine all the functions into a single function? I'm providing my fiddle as well.
I am trying to test it for different scenarios..
but I am not sure how to combine all the scenarios into one..
I am trying to test it for different scenarios..
but I am not sure how to combine all the scenarios into one..
var myNumbersToSort = [null, -1, 2, 0.001, -3, 4, 0.3,1,-0.0001];
function getClosestToZero(set) {
if(0 === set.length) return null;
var closest = set[0], result = 0;
for(var i in set) {
var next = set[i];
if(Math.abs(closest) > Math.abs(next)) {
result = i;
closest = next;
}
}
return closest;
}
function getClosestToZeroWithNaN(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i absVal) {
closest = val;
}
}
}
}
return closest;
}
function getClosestToZeroOnlyNumbers(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i absVal) {
closest = val;
}
}
}
}
return closest;
}
document.getElementById('output').innerHTML = (getClosestToZeroOnlyNumbers(myNumbersToSort));Solution
I think your code would be cleanest if you wrote the program as a composition of a minimum-absolute-value-of-array function and a filter.
Assuming that performance in the face of large data sets is not a concern, you could have, for example:
Alternatively,
Please pay attention to the consistency of the indentation.
Assuming that performance in the face of large data sets is not a concern, you could have, for example:
function isNumber(val) {
return typeof val == "number";
}
getClosestToZero(myNumbersToSort.filter(isNumber));Alternatively,
getClosestToZero() could directly support an optional second argument that servers as a filtering callback if it is provided.Please pay attention to the consistency of the indentation.
Code Snippets
function isNumber(val) {
return typeof val == "number";
}
getClosestToZero(myNumbersToSort.filter(isNumber));Context
StackExchange Code Review Q#37538, answer score: 3
Revisions (0)
No revisions yet.