diff --git a/README.md b/README.md index 1e66c33..081ee29 100644 --- a/README.md +++ b/README.md @@ -527,7 +527,7 @@ chess.isThreefoldRepetition() // -> true ``` -### .load(fen: string, { preserveHeaders = false } = {}) +### .load(fen: string, { skipValidation = false, preserveHeaders = false } = {}) Clears the board and loads the provided FEN string. The castling rights, en passant square and move numbers are defaulted to `- - 0 1` if omitted. Throws an @@ -538,11 +538,14 @@ const chess = new Chess() chess.load('4r3/8/2p2PPk/1p6/pP2p1R1/P1B5/2P2K2/3r4 w - - 1 45') try { - chess.load('4r3/8/X12XPk/1p6/pP2p1R1/P1B5/2P2K2/3r4 w - - 1 45') + chess.load('8/4p3/8/8/8/8/4P3/6K1 w - - 1 45') } catch (e) { console.log(e) } -// -> Error: Invalid FEN: piece data is invalid (invalid piece) +// -> Error: Invalid FEN: missing black king + +chess.load('8/4p3/8/8/8/8/4P3/6K1 w - - 1 45', { skipValidation: true }) +// -> Works! ``` ### .loadPgn(pgn, [ options ]) diff --git a/__tests__/load.test.ts b/__tests__/load.test.ts index f29a845..6d1b81e 100644 --- a/__tests__/load.test.ts +++ b/__tests__/load.test.ts @@ -31,6 +31,18 @@ test('load - bad piece (X)', () => { expect(() => chess.load(fen)).toThrow() }) +test('load - missing white king', () => { + const chess = new Chess() + const fen = '1nbqkbn1/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/1NBQ1BN1 b - - 1 2' + expect(() => chess.load(fen)).toThrow() +}) + +test('load - missing black king', () => { + const chess = new Chess() + const fen = '1nbq1bn1/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/1NBQKBN1 b - - 1 2' + expect(() => chess.load(fen)).toThrow() +}) + test('load - bad ep square (e9)', () => { const chess = new Chess() const fen = 'rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e9 0 1' @@ -61,3 +73,10 @@ test('load - preserveHeaders = true', () => { Black: 'Viswanathan Anand', }) }) + +test('load - skipValidation = true', () => { + const chess = new Chess() + // missing white king + const fen = '1nbqkbn1/pppp1ppp/8/4p3/4P3/8/PPPP1PPP/1NBQ1BN1 b - - 1 2' + expect(() => chess.load(fen, { skipValidation: true })).not.toThrow() +}) diff --git a/src/chess.ts b/src/chess.ts index cf51991..8d61da5 100644 --- a/src/chess.ts +++ b/src/chess.ts @@ -598,7 +598,7 @@ export class Chess { } } - load(fen: string, { preserveHeaders = false } = {}) { + load(fen: string, { skipValidation = false, preserveHeaders = false } = {}) { let tokens = fen.split(/\s+/) // append commonly omitted fen tokens @@ -609,9 +609,11 @@ export class Chess { tokens = fen.split(/\s+/) - const { ok, error } = validateFen(fen) - if (!ok) { - throw new Error(error) + if (!skipValidation) { + const { ok, error } = validateFen(fen) + if (!ok) { + throw new Error(error) + } } const position = tokens[0]