getDisambiguator method Null safety

dynamic getDisambiguator(
  1. Move move
)

Implementation

getDisambiguator(Move move) {
  List<Move> moves = generateMoves();

  var from = move.from;
  var to = move.to;
  var piece = move.piece;

  var ambiguities = 0;
  var sameRank = 0;
  var sameFile = 0;

  for (int i = 0, len = moves.length; i < len; i++) {
    var ambigFrom = moves[i].from;
    var ambigTo = moves[i].to;
    var ambigPiece = moves[i].piece;

    /* if a move of the same piece type ends on the same to square, we'll
     * need to add a disambiguator to the algebraic notation
     */
    if (piece == ambigPiece && from != ambigFrom && to == ambigTo) {
      ambiguities++;

      if (rank(from) == rank(ambigFrom)) {
        sameRank++;
      }

      if (file(from) == file(ambigFrom)) {
        sameFile++;
      }
    }
  }

  if (ambiguities > 0) {
    /* if there exists a similar moving piece on the same rank and file as
     * the move in question, use the square as the disambiguator
     */
    if (sameRank > 0 && sameFile > 0) {
      return algebraic(from);
    } /* if the moving piece rests on the same file, use the rank symbol as the
     * disambiguator
     */
    else if (sameFile > 0) {
      return algebraic(from)[1];
    } /* else use the file symbol */
    else {
      return algebraic(from)[0];
    }
  }

  return '';
}