Skip to content

Commit

Permalink
snapWhenToSteps: support snapping forward
Browse files Browse the repository at this point in the history
  • Loading branch information
derhuerst committed Jan 29, 2024
1 parent c574171 commit 966c393
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/snap-when.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import {strictEqual} from 'node:assert'

// snap `when` to 10s steps for a better cache hit ratio
// Note: With most HAFAs instances, this will yield slightly different results because it all it will return results <=10s in the past.
const snapWhenTo10sSteps = () => {
const now = Date.now()
return now - now % 10 * 1000
const snapWhenTo10sSteps = (t = Date.now(), snapForward = false) => {
t -= t % (10 * 1000)
if (snapForward) t += 10 * 1000
return t
}

strictEqual(snapWhenTo10sSteps(Date.parse('2024-01-29T16:10:50.000+01:00')), Date.parse('2024-01-29T16:10:50+01:00'))
strictEqual(snapWhenTo10sSteps(Date.parse('2024-01-29T16:10:57.812+01:00')), Date.parse('2024-01-29T16:10:50+01:00'))
strictEqual(snapWhenTo10sSteps(Date.parse('2024-01-29T16:11:00.000+01:00')), Date.parse('2024-01-29T16:11:00+01:00'))
strictEqual(snapWhenTo10sSteps(Date.parse('2024-01-29T16:10:57.812+01:00'), true), Date.parse('2024-01-29T16:11:00+01:00'))

export {
snapWhenTo10sSteps as snapWhenToSteps,
}

0 comments on commit 966c393

Please sign in to comment.