DEV Community

Cover image for A horrible coincidence
Ross Angus
Ross Angus

Posted on

A horrible coincidence

Image by Nicolas Poupart

I'm working on some cookie code where the cookie needs to expire one year from now. Well, not exactly. The full story is that the cookie needs to expire no later than one year from now.

This involves the following snippet of JavaScript:

date.setTime(date.getTime()+(365*24*60*60*1000));
Enter fullscreen mode Exit fullscreen mode

That's the number of days in a year, times the number of hours, times... well, you get the picture. Computers are weird: they calculate dates as the number of milliseconds which have passed since New Year 1970.

That calculation above is trivial for a computer and results in the number 31,536,000,000. But could I express it in fewer bytes? My first thought was to express it as a power, using Math.pow(). Math.pow() takes two parameters: the number and the exponent. Perhaps there was a pairing of such numbers which would use the smallest amount of bytes and create a number which was slightly less than 31,536,000,000.

I did the dumb thing: I found a cube-root calculator and started plugging in exponents, until I found a number which rounded down well. The initial number was 9.00179. The exponent was 11. Rounding this down led to a cookie which would expire two days before the deadline.

Excitedly, I updated the code, to see how many bytes I would save:

date.setTime(date.getTime()+Math.pow(9,11));
Enter fullscreen mode Exit fullscreen mode

I glanced at the calendar, and remembered what happened on this day, nineteen years ago. Here's some more numbers: 2,977 people died that day. More than 6,000 were injured. Suddenly the maths seemed less fun.

Note that 911 would produce this rough approximation of the number of milliseconds in a year any time it was calculated. I just happened to stumble upon this today.

Top comments (0)