Which is a better function?

JavaScript performance comparison

Test case created by Vasanth

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Solution One
function solution(digits){
  var numbers = [];
  for (var i = 0; i < digits.length - 4; i++) numbers.push(parseInt(digits.slice(i, i+5)));
  return Math.max.apply(Math, numbers);
Solution Two
function solution(digits){
  var maxIndex=0;
  var maxVal=(digits+"").split("").slice(0,5).join("")*1;  
  var result = (digits+"").split("").reduce(function(a,b,i,arr){
      if(arr[maxIndex] < b ){
        maxVal = arr.slice(i, i+5).join("")*1;
        maxIndex = i;
      else if( arr[maxIndex] == b ){
        maxIndex = (arr.slice(i,i+5).join("")*1) >= maxVal ? i : maxIndex;
        maxVal = arr.slice(maxIndex, maxIndex+5).join("")*1;
      return maxIndex;
  return (digits+"").split("").slice(result,result+5).join("")*1;

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers


Comment form temporarily disabled.

Add a comment