xchess
Version:
Chess Engine
72 lines (64 loc) • 1.73 kB
JavaScript
export const DISAMBIGUATION_NONE = 0;
export const DISAMBIGUATION_FILE = 1;
export const DISAMBIGUATION_RANK = 2;
export const DISAMBIGUATION_FULL = 3;
const DisambiguationMap = new WeakMap();
export function GetMoveDisambiguation(move){
return DisambiguationMap.get(move);
}
export function SetMoveDisambiguation(move, level){
DisambiguationMap.set(move, level)
}
export function ComputeDisambiguationLevels(moves){
const group = GroupMoves(moves);
for(const [key, moves] of group){
if(moves.length > 1)
ComputeLocalDisambiguation(moves);
else for(const move of moves)
SetMoveDisambiguation(move, DISAMBIGUATION_NONE);
}
}
function ComputeLocalDisambiguation(moves){
// Index Moves
const group = new Map();
for(const move of moves){
const {file, rank} = move.from;
const fileMoves = group.get(file);
if(fileMoves)
fileMoves.push(move);
else
group.set(file, [move]);
const rankMoves = group.get(rank);
if(rankMoves)
rankMoves.push(move);
else
group.set(rank, [move]);
}
// Compute Levels
for(const move of moves){
const {file, rank} = move.from;
const fileMoves = group.get(file);
const rankMoves = group.get(rank);
if(fileMoves.length > 1){
if(rankMoves.length > 1)
SetMoveDisambiguation(move, DISAMBIGUATION_FULL);
else
SetMoveDisambiguation(move, DISAMBIGUATION_RANK);
} else SetMoveDisambiguation(move, DISAMBIGUATION_FILE);
}
}
function MoveGroupKey({target, to}){
return `${target.char}${to}`;
}
function GroupMoves(moves){
const group = new Map();
for(const move of moves){
const key = MoveGroupKey(move);
const submoves = group.get(key);
if(submoves)
submoves.push(move);
else
group.set(key, [move]);
}
return group;
}