HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

cleaning up and increasing performance of js code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
codeincreasingperformanceandcleaning

Problem

I would like to increase my performance of js code write a clean code... can you tell me how to do it... providing my fiddle below with js code...

http://jsfiddle.net/YYg8U/

var myNumbersToSort = [-1, 2, -3, 4, 0.3, -0.001];

function getClosestToZero(numberSet) {
    var i = 0, positiveSet = [], positiveClosest = 0;
    for (i = 0; i = 0 ? numberSet[i] : numberSet[i] * -1);
    }
    positiveClosest = Math.min.apply(Math, positiveSet);
    return numberSet[positiveSet.indexOf(positiveClosest)];
}

alert(getClosestToZero(myNumbersToSort));

Solution

In code you posted, you pass through array three times instead of one:

-
1st pass when pushing absolute values to auxillary array

-
2nd pass when searching for minimum value (in Math.min)

-
3rd pass when you get the index of minimum value (in indexOf)

It is more efficiently to do it in just one pass:

function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = Math.abs(set[0]), result = 0;
  for(var i in set) {
     var next = Math.abs(set[i]);
     if(closest > next) {
       result = i;
       closest = next;
     }
  }
  return result;  
}


Also for the purpose of readability I will recommend you to use Math.abs library function instead of implementing it by yourself.

Note: The small theoretical disatavantage of my code consists in that it compares first element with itself. You can rewrite for loop to avoid it or ignore it because its impact is insigninficant.

Code Snippets

function getClosestToZero(set) {
  if(0 === set.length) return null;
  var closest = Math.abs(set[0]), result = 0;
  for(var i in set) {
     var next = Math.abs(set[i]);
     if(closest > next) {
       result = i;
       closest = next;
     }
  }
  return result;  
}

Context

StackExchange Code Review Q#37352, answer score: 5

Revisions (0)

No revisions yet.