refactor: enforce integers in numbers

This commit is contained in:
cv
2023-09-29 22:10:40 +02:00
parent 8146d88765
commit d9df866308
3 changed files with 18 additions and 6 deletions
@@ -525,7 +525,7 @@ describe('test event validator', () => {
expect(typeof validated.timeStart).toEqual('number'); expect(typeof validated.timeStart).toEqual('number');
expect(validated.timeStart).toEqual(0); expect(validated.timeStart).toEqual(0);
expect(typeof validated.timeEnd).toEqual('number'); expect(typeof validated.timeEnd).toEqual('number');
expect(validated.timeEnd).toEqual(0); expect(validated.timeEnd).toEqual(2);
}); });
it('handles bad objects', () => { it('handles bad objects', () => {
@@ -86,4 +86,11 @@ describe('validateTimes()', () => {
expect(timeEnd).toBe(10); expect(timeEnd).toBe(10);
expect(duration).toBe(10); expect(duration).toBe(10);
}); });
it('ensures values are integers', () => {
const { timeStart, timeEnd, duration } = validateTimes(0.000001, 10.312335342, 10);
expect(timeStart).toBe(0);
expect(timeEnd).toBe(10);
expect(duration).toBe(10);
});
}); });
@@ -40,10 +40,15 @@ export const calculateDuration = (timeStart: number, timeEnd: number): number =>
return timeEnd - timeStart; return timeEnd - timeStart;
}; };
export function validateTimes(_start?: number | null, _end?: number | null, _duration?: number | null) { function convertToInteger(value: unknown): number {
const timeStart = _start ?? 0; const result = Number(value);
const timeEnd = _end ?? 0; return isNaN(result) ? 0 : Math.floor(result);
const duration = _duration ?? 0; }
export function validateTimes(_start?: unknown, _end?: unknown, _duration?: unknown) {
const timeStart = convertToInteger(_start);
const timeEnd = convertToInteger(_end);
const duration = convertToInteger(_duration);
if (_start != null && _end != null) { if (_start != null && _end != null) {
// Case 1. if we have start and end, duration must be derived // Case 1. if we have start and end, duration must be derived
@@ -56,7 +61,7 @@ export function validateTimes(_start?: number | null, _end?: number | null, _dur
return { timeStart, duration, timeEnd }; return { timeStart, duration, timeEnd };
} }
// Case 3. we have a duration and infer the rest // Case 3. we have a duration and infer the rest
return { timeStart, duration: _duration, timeEnd: _duration }; return { timeStart, duration, timeEnd: duration };
} }
if (_start != null) { if (_start != null) {