Skip to content

Commit

Permalink
Add extendMainline to PGN/game
Browse files Browse the repository at this point in the history
  • Loading branch information
kraktus committed Jan 21, 2024
1 parent 9f15cc2 commit 22eb522
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/pgn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
parsePgn,
transform,
startingPosition,
defaultGame,
emptyHeaders,
extendMainline,
parseComment,
makeComment,
isChildNode,
Expand Down Expand Up @@ -79,6 +81,17 @@ test('make pgn', () => {
);
});

test('extend mainline', () => {
let game: Game<PgnNodeData> = defaultGame(emptyHeaders);
const mainline = 'e4 d5 a3 h6 Bg5'.split(' ').map(san => {
return {
san: san,
};
});
extendMainline(game, mainline);
expect(makePgn(game)).toEqual('1. e4 d5 2. a3 h6 3. Bg5 *\n');
});

test('parse headers', () => {
const games = parsePgn(
[
Expand Down
13 changes: 13 additions & 0 deletions src/pgn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,19 @@ export class Node<T> {
}
}

export const extendMainline = <T>(game: Game<T>, data: T[]) => {
let node = game.moves;
while (node.children.length) {
const child = node.children[0];
node = child;
}
data.forEach(d => {
const newNode = new ChildNode(d);
node.children = [newNode];
node = newNode;
});
};

export class ChildNode<T> extends Node<T> {
constructor(public data: T) {
super();
Expand Down

0 comments on commit 22eb522

Please sign in to comment.