Skip to content
This repository was archived by the owner on Nov 20, 2025. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions serverDate.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,15 @@ const fetchSampleImplementation = async () => {
};

export const getServerDate = async (
{ fetchSample } = { fetchSample: fetchSampleImplementation }
{ fetchSample, withErrors } = { fetchSample: fetchSampleImplementation, withErrors: false }
) => {
let best = { uncertainty: Number.MAX_VALUE };
const fetchCount = 10;
const errors = [];
let best = { date: new Date(), offset: 0, uncertainty: Number.MAX_VALUE };

// Fetch 10 samples to increase the chance of getting one with low
// uncertainty.
for (let index = 0; index < 10; index++) {
for (let index = 0; index < fetchCount; index++) {
try {
const { requestDate, responseDate, serverDate } = await fetchSample();

Expand All @@ -46,9 +48,10 @@ export const getServerDate = async (
};
}
} catch (exception) {
errors.push(exception);
console.warn(exception);
}
}

return best;
return withErrors ? { ...best, errors, fetchCount } : best;
};
19 changes: 19 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,22 @@ it(`synchronizes the time with the server`, async () => {
uncertainty: 582.5,
});
});

it(`returns offset 0 and local Date on error`, async () => {
const fetchSample = async () => {
throw new Error(`oh dang`);
};
const { date, offset, uncertainty } = await getServerDate({ fetchSample });
assert(offset === 0);
assert(uncertainty === Number.MAX_VALUE);
assert(Date.now() - date < 100);
})

it(`reports errors if you ask it to`, async () => {
const fetchSample = async () => {
throw new Error(`oh dang`);
};
const { errors, fetchCount } = await getServerDate({ fetchSample, withErrors: true });
assert(errors.length === fetchCount);
assert(errors[0].message === `oh dang`);
})