From bfae2b12e00843202315f0b55a8d9eeb2fd5e1bd Mon Sep 17 00:00:00 2001 From: Rene Saarsoo Date: Sat, 26 Dec 2020 17:31:01 +0200 Subject: [PATCH] Detect overlapping comments --- src/parser/parser.test.ts | 26 ++++++++++++++++++++++++++ src/parser/validate.ts | 10 +++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/parser/parser.test.ts b/src/parser/parser.test.ts index c1a9894..82ba192 100644 --- a/src/parser/parser.test.ts +++ b/src/parser/parser.test.ts @@ -664,4 +664,30 @@ Interval: 2:00 90% `), ).toThrowErrorMatchingInlineSnapshot(`"Negative comment offset is larger than interval length at line 5 char 5"`); }); + + it("throws error when comment offset is the same as another comment offset", () => { + expect(() => + parse(` +Name: My Workout +Interval: 2:00 90% + @ 0:00 First comment + @ 1:00 Comment + @ 1:00 Overlapping comment + @ 1:50 Last comment +`), + ).toThrowErrorMatchingInlineSnapshot(`"Comment overlaps previous comment at line 6 char 5"`); + }); + + it("throws error when comment offset is greater than next comment offset", () => { + expect(() => + parse(` +Name: My Workout +Interval: 2:00 90% + @ 0:00 First comment + @ 1:20 Comment + @ 1:00 Misplaced comment + @ 1:50 Last comment +`), + ).toThrowErrorMatchingInlineSnapshot(`"Comment overlaps previous comment at line 6 char 5"`); + }); }); diff --git a/src/parser/validate.ts b/src/parser/validate.ts index 0830450..2902ae7 100644 --- a/src/parser/validate.ts +++ b/src/parser/validate.ts @@ -1,14 +1,18 @@ import { Workout, Interval } from "../ast"; import { ValidationError } from "./ValidationError"; -const validateCommentOffsets = (interval: Interval) => { - for (const comment of interval.comments) { - if (comment.offset.seconds >= interval.duration.seconds) { +const validateCommentOffsets = ({ comments, duration }: Interval) => { + for (let i = 0; i < comments.length; i++) { + const comment = comments[i]; + if (comment.offset.seconds >= duration.seconds) { throw new ValidationError(`Comment offset is larger than interval length`, comment.loc); } if (comment.offset.seconds < 0) { throw new ValidationError(`Negative comment offset is larger than interval length`, comment.loc); } + if (i > 0 && comment.offset.seconds <= comments[i - 1].offset.seconds) { + throw new ValidationError(`Comment overlaps previous comment`, comment.loc); + } } };