UNPKG

884 BJavaScriptView Raw
1/**
2 * Utility helpers for working with numbers.
3 *
4 * @module number
5 */
6
7import * as math from './math.js'
8import * as binary from './binary.js'
9
10export const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER
11export const MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER
12
13export const LOWEST_INT32 = 1 << 31
14export const HIGHEST_INT32 = binary.BITS31
15export const HIGHEST_UINT32 = binary.BITS32
16
17/* c8 ignore next */
18export const isInteger = Number.isInteger || (num => typeof num === 'number' && isFinite(num) && math.floor(num) === num)
19export const isNaN = Number.isNaN
20export const parseInt = Number.parseInt
21
22/**
23 * Count the number of "1" bits in an unsigned 32bit number.
24 *
25 * Super fun bitcount algorithm by Brian Kernighan.
26 *
27 * @param {number} n
28 */
29export const countBits = n => {
30 n &= binary.BITS32
31 let count = 0
32 while (n) {
33 n &= (n - 1)
34 count++
35 }
36 return count
37}