-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(runner): virtualize time keeping
- Loading branch information
Showing
4 changed files
with
87 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/** @typedef {number} TimeValueS */ | ||
|
||
/** | ||
* @param {number} [resolution] number of decimal digits | ||
* @param {number} [inputAdjustment] number of decimal digits the input is already shifted | ||
*/ | ||
export const makeRounder = (resolution = 6, inputAdjustment = 0) => { | ||
const factor = 10 ** resolution; | ||
const valueFactor = 10 ** (resolution - inputAdjustment); | ||
/** | ||
* @param {number} value | ||
* @returns {number} | ||
*/ | ||
return (value) => Math.round(value * valueFactor) / factor; | ||
}; | ||
|
||
/** | ||
* @param {Object} param0 | ||
* @param {Pick<Performance, 'timeOrigin' | 'now'>} param0.performance | ||
* @param {number} [param0.resolution] number of decimal digits | ||
* @param {TimeValueS} [param0.offset] origin offset to apply | ||
*/ | ||
export const makeTimeSource = ({ | ||
performance, | ||
resolution = 6, | ||
offset: initialOffset = 0, | ||
}) => { | ||
const offsetMs = initialOffset * 1000; | ||
const rounder = makeRounder(resolution, 3); | ||
|
||
const timeOrigin = rounder(performance.timeOrigin + offsetMs); | ||
const getTime = () => rounder(performance.timeOrigin + performance.now()); | ||
const now = () => rounder(performance.now() - offsetMs); | ||
const shift = (offset = now()) => | ||
makeTimeSource({ performance, resolution, offset: offset + initialOffset }); | ||
|
||
return { timeOrigin, getTime, now, shift }; | ||
}; | ||
|
||
/** @typedef {ReturnType<makeTimeSource>} TimeSource */ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters