3
\$\begingroup\$

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));
asked Dec 16, 2013 at 20:11
\$\endgroup\$
1
  • \$\begingroup\$ Keyword: transducers \$\endgroup\$ Commented Dec 2, 2022 at 2:37

1 Answer 1

3
\$\begingroup\$

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.

answered Dec 16, 2013 at 20:43
\$\endgroup\$
2
  • \$\begingroup\$ thanks for your reply...can you update in the fiddle jsfiddle.net/hB2T8 its confusing \$\endgroup\$ Commented 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\$ Commented Dec 16, 2013 at 21:50

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.