Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Created April 21, 2016 03:13
Show Gist options
  • Save pmuellr/4b12b28c9856ab12930b6979cb0daf6b to your computer and use it in GitHub Desktop.
Save pmuellr/4b12b28c9856ab12930b6979cb0daf6b to your computer and use it in GitHub Desktop.
how many microseconds fit in a safe JS integer?
'use strict'
const max = Number.MAX_SAFE_INTEGER // 9007199254740991
console.log('Number.MAX_SAFE_INTEGER: ', nice(max))
console.log('')
// Number.MAX_SAFE_INTEGER: 9,007,199,254,740,991
console.log('how many time units fit in', nice(max), 'microseconds')
const unitScs = max / 1000 / 1000
const unitMns = unitScs / 60
const unitHrs = unitMns / 60
const unitDys = unitHrs / 24
const unitYrs = unitDys / 365
// how many seconds fit in MAX_SAFE_INTEGER?
console.log(' seconds:', nice(unitScs))
console.log(' minutes:', nice(unitMns))
console.log(' hours: ', nice(unitHrs))
console.log(' days: ', nice(unitDys))
console.log(' years: ', nice(unitYrs))
// how many time units fit in 9,007,199,254,740,991 microseconds
// seconds: 9,007,199,255
// minutes: 150,119,988
// hours: 2,502,000
// days: 104,250
// years: 286
// double check the years value
const check = unitYrs * 365 * 24 * 60 * 60 * 1000 * 1000
console.log('')
console.log('double checking the years value:')
console.log(' years as microseconds: ', nice(check))
console.log(' Number.MAX_SAFE_INTEGER - that:', nice(max - check))
// double checking the years value:
// years as microseconds: 9,007,199,254,740,990
// Number.MAX_SAFE_INTEGER - that: 1
function nice(n) {
return right(commaize(ceil(n)), 21)
}
function right(s, len, pad) {
pad = pad || ' '
s = '' + s
while (s.length < len) s = pad + s
return s
}
function commaize(n) {
n = '' + n
n = reverse(n)
let result = []
while (n.length > 0) {
result.push(reverse(n.substr(0, 3)))
n = n.substr(3)
}
return result.reverse().join(',')
}
function ceil(n) { return Math.ceil(n) }
function reverse(s) { return s.split('').reverse().join('')}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment