diff --git a/src/utils/__tests__/parseChapterNumber.test.ts b/src/utils/__tests__/parseChapterNumber.test.ts new file mode 100644 index 00000000..d4c3b561 --- /dev/null +++ b/src/utils/__tests__/parseChapterNumber.test.ts @@ -0,0 +1,33 @@ +import { parseChapterNumber } from '../parseChapterNumber'; + +describe('parseChapterNumber', () => { + it('returns the provided chapterNumber when valid', () => { + expect(parseChapterNumber('Novel', 'Chapter 5', 5)).toBe(5); + }); + + it('parses a basic chapter number from the name', () => { + expect(parseChapterNumber('Novel', 'Chapter 12')).toBe(12); + }); + + it('does not throw when chapterName is undefined', () => { + expect(parseChapterNumber('Novel', undefined as unknown as string)).toBe( + -1, + ); + }); + + it('does not throw when chapterName is null', () => { + expect(parseChapterNumber('Novel', null as unknown as string)).toBe(-1); + }); + + it('falls back to the given chapterNumber when chapterName is missing', () => { + expect( + parseChapterNumber('Novel', undefined as unknown as string, -1), + ).toBe(-1); + }); + + it('does not throw when novelName is undefined', () => { + expect( + parseChapterNumber(undefined as unknown as string, 'Chapter 3'), + ).toBe(3); + }); +}); diff --git a/src/utils/parseChapterNumber.ts b/src/utils/parseChapterNumber.ts index 97b8b8d0..29520bac 100644 --- a/src/utils/parseChapterNumber.ts +++ b/src/utils/parseChapterNumber.ts @@ -9,6 +9,10 @@ export const parseChapterNumber = ( return chapterNumber; } + if (!chapterName) { + return chapterNumber ?? -1; + } + const basic = new RegExp(/(?<=ch[^\d]*[\s]*)([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?/); const number = new RegExp(/([0-9]+)(\.[0-9]+)?(\.?[a-z]+)?/); const unwantedWhiteSpace = new RegExp(/\s(?=extra|special|omake)/g); @@ -16,7 +20,7 @@ export const parseChapterNumber = ( /\b(?:v|ver|vol|version|volume|season|s)[^a-z]?[0-9]+/g, ); let name = chapterName.toLowerCase(); - name = name.replace(novelName.toLowerCase(), '').trim(); + name = name.replace((novelName ?? '').toLowerCase(), '').trim(); name = name.replace(',', '.').replace('-', '.'); name = name.replace(unwantedWhiteSpace, ''); name = name.replace(unwanted, '');