Skip to content

Instantly share code, notes, and snippets.

@priithaamer
Created October 3, 2014 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save priithaamer/2ba52969bad4cd8013cd to your computer and use it in GitHub Desktop.
Save priithaamer/2ba52969bad4cd8013cd to your computer and use it in GitHub Desktop.
var play = function() {
var boxes = $('#box span');
var colors = boxes.map(function(idx, item) {
return $(item).css('background-color');
});
var color1 = {color: $.unique(colors)[0], count: 0};
var color2 = {color: $.unique(colors)[1], count: 0};
boxes.each(function(idx, item) {
if ($(item).css('background-color') == color1.color) {
color1.count++;
} else {
color2.count++;
}
});
if (color1.count < color2.count) {
$('#box span[style*="' + color1.color + '"]').eq(0).click();
} else {
$('#box span[style*="' + color2.color + '"]').eq(0).click();
}
setTimeout(play, 1);
}
@pulges
Copy link

pulges commented Oct 3, 2014

Minor speed improvement:

$('#box').css('display', 'none');
var play = function() {
  var boxes = $('#box span'), 
      color1 = {count: 0},
      color2 = {count: 0},
      lastColor1Item, lastColor2Item;

  boxes.each(function(idx, item) {
    var color = $(item).css('background-color');
    if (!color1.color) {
      color1.color = color;
    }
    if (color == color1.color) {
      color1.count++;
      lastColor1Item = item;
    } else {
      if (!color2.color) {
          color2.color = color;
      }
      color2.count++;
      lastColor2Item = item;
    }
  });

  if (color1.count < color2.count) {
    $(lastColor1Item).click();
  } else {
    $(lastColor2Item).click();
  }

  setTimeout(play, 0);
}

@pulges
Copy link

pulges commented Oct 3, 2014

Breaking the each loop in the right moment improves even more with:

if (color1.color && color2.color && (color1.count > 1 || color2.count > 1)) {
  return false;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment