Validate comment offsets

This commit is contained in:
Rene Saarsoo 2020-11-21 20:58:00 +02:00
parent 51590f1f61
commit 1a720c2b21
4 changed files with 39 additions and 1 deletions

View File

@ -0,0 +1,5 @@
export class ValidationError extends Error {
constructor(msg: string) {
super(msg);
}
}

View File

@ -1,5 +1,6 @@
import { Workout } from "../ast";
import { parseTokens } from "./parser";
import { tokenize } from "./tokenizer";
import { validate } from "./validate";
export const parse = (source: string): Workout => parseTokens(tokenize(source));
export const parse = (source: string): Workout => validate(parseTokens(tokenize(source)));

View File

@ -526,4 +526,17 @@ Rest: 5:00 50%
}
`);
});
it("throws error when comment offset is outside of interval length", () => {
expect(() =>
parse(`
Name: My Workout
Interval: 2:00 90%
@ 0:00 Find your rythm.
@ 3:10 Try to settle in for the effort
`),
).toThrowErrorMatchingInlineSnapshot(
`"Comment \\"@ 190 Try to settle in for the effort\\" has offset outside of interval"`,
);
});
});

19
src/parser/validate.ts Normal file
View File

@ -0,0 +1,19 @@
import { Workout, Interval, Comment } from "../ast";
import { ValidationError } from "./ValidationError";
const isCommentWithinInterval = (comment: Comment, interval: Interval): boolean => {
return comment.offset.seconds < interval.duration.seconds;
};
const validateCommentOffsets = (interval: Interval) => {
for (const comment of interval.comments) {
if (!isCommentWithinInterval(comment, interval)) {
throw new ValidationError(`Comment "@ ${comment.offset.seconds} ${comment.text}" has offset outside of interval`);
}
}
};
export const validate = (workout: Workout): Workout => {
workout.intervals.forEach(validateCommentOffsets);
return workout;
};