From 22eb522dad77fce4780d5cf304a10698d24cadf7 Mon Sep 17 00:00:00 2001 From: kraktus Date: Sun, 21 Jan 2024 16:28:58 +0100 Subject: [PATCH] Add `extendMainline` to PGN/game --- src/pgn.test.ts | 13 +++++++++++++ src/pgn.ts | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/pgn.test.ts b/src/pgn.test.ts index 54bd0906..9d20057a 100644 --- a/src/pgn.test.ts +++ b/src/pgn.test.ts @@ -10,7 +10,9 @@ import { parsePgn, transform, startingPosition, + defaultGame, emptyHeaders, + extendMainline, parseComment, makeComment, isChildNode, @@ -79,6 +81,17 @@ test('make pgn', () => { ); }); +test('extend mainline', () => { + let game: Game = 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( [ diff --git a/src/pgn.ts b/src/pgn.ts index 59037e99..daac3448 100644 --- a/src/pgn.ts +++ b/src/pgn.ts @@ -131,6 +131,19 @@ export class Node { } } +export const extendMainline = (game: Game, 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 extends Node { constructor(public data: T) { super();