fix: guard against large numbers

Guard against numbers beyond MAX_SAFE_INTEGER and reset count if necessary.
This commit is contained in:
Ayane Satomi 2023-10-22 05:45:44 +00:00
parent 09378ab37d
commit be94406c49

View file

@ -54,14 +54,16 @@ export default function Counter(props: SharedProps) {
setCount(count + 1); setCount(count + 1);
animateMascot(); animateMascot();
let audioFile = props.audioFiles[Math.floor(Math.random() * props.audioFiles.length)]; let audioFile =
props.audioFiles[Math.floor(Math.random() * props.audioFiles.length)];
let lastAudioPlayed = audioFile; let lastAudioPlayed = audioFile;
const audio = new Audio(); const audio = new Audio();
// Check if the audio file is the same as the last one played // Check if the audio file is the same as the last one played
// If so, pick another one // If so, pick another one
if (lastAudioPlayed === audioFile) { if (lastAudioPlayed === audioFile) {
audioFile = props.audioFiles[Math.floor(Math.random() * props.audioFiles.length)]; audioFile =
props.audioFiles[Math.floor(Math.random() * props.audioFiles.length)];
lastAudioPlayed = audioFile; lastAudioPlayed = audioFile;
audio.src = audioFile; audio.src = audioFile;
} else { } else {
@ -70,18 +72,26 @@ export default function Counter(props: SharedProps) {
audio.play(); audio.play();
clearTimeout(timer); clearTimeout(timer);
setTimer(setTimeout(() => { setTimer(setTimeout(() => {
console.info( console.info(
`[${new Date()}] Updating global count: ${internalCount + 1}`, `[${new Date()}] Updating global count: ${internalCount + 1}`,
); );
// guard against numbers that are beyond MAX_SAFE_INTEGER.
if (internalCount === Number.MAX_SAFE_INTEGER) {
console.warn(
"Data too large to be submitted and represented safely. Disposing.",
);
setCount(0);
setInternalCount(0);
} else {
axios.post( axios.post(
window.location.href, window.location.href,
JSON.stringify({ data: internalCount + 1 }), JSON.stringify({ data: internalCount + 1 }),
); );
setInternalCount(0); setInternalCount(0);
}
}, 5000)); }, 5000));
}; };