Skip to content

Commit

Permalink
Merge remote-tracking branch 'kraktus/extendMainline'
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Jan 24, 2024
2 parents 1a7c478 + f3f5fd3 commit 2686292
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/pgn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { Position } from './chess.js';
import { makeFen } from './fen.js';
import {
ChildNode,
defaultGame,
emptyHeaders,
extendMainline,
Game,
isChildNode,
makeComment,
Expand Down Expand Up @@ -40,7 +42,7 @@ function testPgnFile({ fileName = '', numberOfGames = 1, allValid = true } = {},
.on('close', () => {
parser.parse('');
expect(gameCallback).toHaveBeenCalledTimes(numberOfGames);
done();
done!();
});
});
}
Expand Down Expand Up @@ -79,6 +81,17 @@ test('make pgn', () => {
);
});

test('extend mainline', () => {
let game: Game<PgnNodeData> = defaultGame(emptyHeaders);

Check warning on line 85 in src/pgn.test.ts

View workflow job for this annotation

GitHub Actions / build

'game' is never reassigned. Use 'const' instead
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 2686292

Please sign in to comment.