node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
timer.js
(674B)
1 const nextInterval = (start, interval) => {
2 const currentSeconds = Math.ceil(new Date() / 1000);
3 const startSeconds = Math.floor(new Date(start).getTime() / 1000);
4 const next = Math.ceil((currentSeconds - startSeconds) / interval) * interval;
5 return new Date((startSeconds + next) * 1000);
6 };
7
8 const timer = session => {
9 const { createdAt, gameIntervalInSeconds } = session;
10 const nextIntervalAt = nextInterval(createdAt, gameIntervalInSeconds);
11 const expiring = nextIntervalAt >= session.expiresAt;
12
13 return expiring ? {} : {
14 nextIntervalAt,
15 nextIntervalInMillis: nextIntervalAt - Date.now(),
16 };
17 };
18
19 export default timer;