Skip to content

Instantly share code, notes, and snippets.

@anthony-dandrea
Last active August 29, 2015 14:08
Show Gist options
  • Save anthony-dandrea/449daca1c314b8b4ab2a to your computer and use it in GitHub Desktop.
Save anthony-dandrea/449daca1c314b8b4ab2a to your computer and use it in GitHub Desktop.
HW Nov 12th 2014
// 1. I feel like you already answered the question.
// But say if the very first case in winCombos is a win,
// the reduce method will go through the rest of the cases
// regards of the early win find.
// 2. 21 times because total of 8 winCombos and 3 within
// each. So 8 - 1 = 7, 7 * 3 21.
// 3. When it would be iterating through the last winCombos
// and finds the [0] != [1] in the array.
// 4. It would be called 1 time unnecessarily.
// 5. checkForWin() rewrite
/////////////////////////////////
// Old Version
/////////////////////////////////
Grid.prototype.checkForWin = function() {
//var surroundingVectors = this.getSurroundingVectors(index);
var winCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]];
var self = this;
//The current win combo reduce needs to be refactored into it's own function
return winCombos.reduce(function(previousValue, currentWinCombo) {
return previousValue || currentWinCombo.reduce(function(w,el,i,arr){
return w && (arr.length-1 == i || (self.vectors[el].value != null && self.vectors[el].value == self.vectors[arr[i+1]].value))
}, true)
}, false)
}
/////////////////////////////////
// Rewrite Version
/////////////////////////////////
Grid.prototype.checkForWin = function() {
//var surroundingVectors = this.getSurroundingVectors(index);
var winCombos = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]];
var self = this;
// Fuck reduce
return winCombos.some(function(element, index, array) {
var currentCombo = [self.vectors[element[0]].value, self.vectors[element[1]].value, self.vectors[element[2]].value];
return currentCombo.indexOf(null) === -1 &&
currentCombo[0] === currentCombo[1] && currentCombo[0] === currentCombo[2];
})
}
@anthony-dandrea
Copy link
Author

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