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..
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 < set.length; i++) {
var val = set[i];
if(!isNaN(val)){
val = Number(val);
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
function getClosestToZeroOnlyNumbers(set) {
var closest;
if(set instanceof Array) {
for(var i = 0; i < set.length; i++) {
var val = set[i];
if(typeof val == "number"){
var absVal = Math.abs(val);
if(typeof closest == 'undefined' || Math.abs(closest) > absVal) {
closest = val;
}
}
}
}
return closest;
}
document.getElementById('output').innerHTML = (getClosestToZeroOnlyNumbers(myNumbersToSort));
-
\$\begingroup\$ Keyword: transducers \$\endgroup\$morbusg– morbusg2022年12月02日 02:37:35 +00:00Commented Dec 2, 2022 at 2:37
1 Answer 1
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:
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.
-
\$\begingroup\$ thanks for your reply...can you update in the fiddle jsfiddle.net/hB2T8 its confusing \$\endgroup\$user3102494– user31024942013年12月16日 20:46:45 +00:00Commented Dec 16, 2013 at 20:46
-
\$\begingroup\$ According to our help center rules, asking for code to be written is off-topic for Code Review. The original question was marginal; your request would definitely violate our community's standards. \$\endgroup\$200_success– 200_success2013年12月16日 21:50:22 +00:00Commented Dec 16, 2013 at 21:50