Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

210
Vistas
Avoiding nested loops in a TicTacToe algorithm JavaScript

I wrote a quick algorithm that detects a win in a TicTacToe Game.

function game() loops through a simulated ticTacToe board, finds all the index's of a given value, then loops through all the possible winning combos, finds any index's where the actual value is equal to the index's from the first loop, (I know :/) then replaces the value with the value passed into the function (either x or o).

Then, a subsequent function is run that checks if every value inside any of the nested arrays inside the possibleWinCombos are all equal to each other. If true, a winner is found.

const possibleWinCombos = [
  [0, 1, 2], //================ //
  [3, 4, 5],  //== Horizontal == //
  [6, 7, 8],  //=================//

  [0, 3, 6],  //================ //
  [1, 4, 7],  //== Vertical == //
  [2, 5, 8],  //=================//
  
  [0, 4, 8],  //=================//
  [2, 4, 6],  //== Diagonal == //
]

const ticTacToe = [
  'x', 'o', null,
  null, 'x', null,
  'o', null, 'x',
]

const game = (value) => {
  ticTacToe.forEach((cell, idxOfCell) => {
    if(cell === value){
      for (winCombo of possibleWinCombos){
        let idxToReplace = winCombo.indexOf(idxOfCell) 
        winCombo.splice(idxToReplace, 1, value)
      }     
    }
  })
  
  checkForWinner(value) ? 
    console.log(`${value}'s win`) : console.log('game still going')
}

const checkForWinner = (value) => {
  return possibleWinCombos.some((winCombo) => {
    return winCombo.every((winComboValue) => winComboValue === value);
  })  
}

game('x') // x's win
game('o') // game still going

It's only two functions so it's not very code heavy but I feel like game() wouldn't score very high on the performance rankings due to the nested looping. Any recommendations on some improvements would be great.

https://replit.com/@uwitdat/DrabNoteworthyLogin#script.js

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda