Sha256: fdfe57eec8440a6d1be51508867d38df3d3a0b88224e8673127561821d56574d

Contents?: true

Size: 1.24 KB

Versions: 27

Compression:

Stored size: 1.24 KB

Contents

const W = 8,
  H = 8,
  STARTING = { black: [7, 3], white: [0, 3] };

const QueenAttack = (params = STARTING) => {
  const self = this instanceof QueenAttack ? this : Object.getPrototypeOf(QueenAttack);
  if (params && params.white === params.black) {
    throw new Error('Queens cannot share the same space');
  }

  self.black = params.black;
  self.white = params.white;
  self.board = constructBoard();
  placePieces(self);

  self.canAttack = () => {
    if (self.black[0] === self.white[0] || self.black[1] === self.white[1]) {
      return true;
    }
    return Math.abs(self.black[0] - self.white[0]) === Math.abs(self.black[1] - self.white[1]);
  };

  self.toString = () => self.board.join('');

  return self;
};

function constructBoard() {
  let row = buildRow('_ ', W).join('');
  row = `${row.substring(0, row.length - 1)}\n`;
  return concatRows(row, H);
}

function placePieces(self) {
  self.board[self.black[0] * W * 2 + self.black[1] * 2] = 'B';
  self.board[self.white[0] * W * 2 + self.white[1] * 2] = 'W';
}

function buildRow(cell, colCount) {
  return Array(...Array(colCount)).map(() => cell);
}

function concatRows(row, rowCount) {
  return [...Array.prototype.concat.apply(buildRow(row, rowCount)).join('')];
}

export default QueenAttack;

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
trackler-2.2.1.20 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.19 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.18 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.17 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.16 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.15 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.14 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.13 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.12 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.11 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.10 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.9 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.8 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.7 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.6 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.5 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.4 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.3 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.2 tracks/ecmascript/exercises/queen-attack/example.js
trackler-2.2.1.1 tracks/ecmascript/exercises/queen-attack/example.js