Sha256: 2df998f3d3094a62f6e51cc3890a483cffe7c450b020afc4ca42a19e573ad9b9

Contents?: true

Size: 1.09 KB

Versions: 185

Compression:

Stored size: 1.09 KB

Contents

const MINE = '*';

const DELTAS = [
  [-1, -1],
  [-1, 0],
  [-1, 1],
  [1, 1],
  [1, 0],
  [1, -1],
  [0, 1],
  [0, -1],
];

class Minesweeper {
  annotate(rows) {
    if (noDataPresent(rows)) {
      return rows;
    }

    const inputBoard = rows.map(row => [...row]);

    return stringify(
      inputBoard.map((row, x) => [...row].map((cell, y) => cellToMineOrCount(cell, inputBoard, x, y))),
    );
  }
}

function cellToMineOrCount(cell, inputBoard, x, y) {
  if (cell === MINE) {
    return MINE;
  } 
    return countAdjacentMines(inputBoard, x, y) || " ";
  
}

function countAdjacentMines(board, x, y) {
  return DELTAS
    .filter(d => adjacentSquareIsOnBoard(board, x, d))
    .filter(d => adjacentSquareHasMine(board, x, y, d))
    .length;
}

function stringify(board) {
  return board.map(row => row.join(''));
}

function noDataPresent(rows) {
  return rows.length === 0 || rows[0].length === 0;
}

function adjacentSquareIsOnBoard(board, x, d) {
  return board[x + d[0]];
}

function adjacentSquareHasMine(board, x, y, d) {
  return board[x + d[0]][y + d[1]] === MINE;
}


export default Minesweeper;

Version data entries

185 entries across 185 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.179 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.178 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.177 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.176 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.175 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.174 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.173 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.172 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.171 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.170 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.169 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.167 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.166 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.165 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.164 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.163 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.162 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.161 tracks/ecmascript/exercises/minesweeper/example.js
trackler-2.2.1.160 tracks/ecmascript/exercises/minesweeper/example.js