All files / blong-gogo/src timing.ts

55.17% Statements 16/29
100% Branches 1/1
20% Functions 1/5
55.17% Lines 16/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 301x 1x 1x 11x   11x 11x 11x 11x                     11x     11x 11x 11x 11x 1x 1x 1x  
import type {HRTime} from '@feasibleone/blong/types';
 
const timing = (now: (previous?: HRTime) => HRTime) => {
    const diff = (time: HRTime, newTime: HRTime) =>
        (newTime[0] - time[0]) * 1000 + (newTime[1] - time[1]) / 1000000;
 
    return {
        diff,
        after: (milliseconds: number) => {
            const seconds = Math.floor(milliseconds / 1000);
            const result = now();
            result[1] += Math.floor((milliseconds - seconds * 1000) * 1000000);
            result[0] += seconds;
            if (result[1] >= 1000000000) {
                result[0]++;
                result[1] -= 1000000000;
            }
            return result;
        },
        isAfter: (time: HRTime, timeout: HRTime) =>
            Array.isArray(timeout) &&
            (time[0] > timeout[0] || (time[0] === timeout[0] && time[1] > timeout[1])),
        spare: (time: HRTime, latency?: number) => Math.floor(diff(now(), time)) - (latency || 0),
        now,
    };
};
 
export type ITiming = ReturnType<typeof timing>;
export default timing;