UNPKG

1.56 kBJavaScriptView Raw
1/**
2 * Utility module to convert metric values.
3 *
4 * @module metric
5 */
6
7import * as math from './math.js'
8
9export const yotta = 1e24
10export const zetta = 1e21
11export const exa = 1e18
12export const peta = 1e15
13export const tera = 1e12
14export const giga = 1e9
15export const mega = 1e6
16export const kilo = 1e3
17export const hecto = 1e2
18export const deca = 10
19export const deci = 0.1
20export const centi = 0.01
21export const milli = 1e-3
22export const micro = 1e-6
23export const nano = 1e-9
24export const pico = 1e-12
25export const femto = 1e-15
26export const atto = 1e-18
27export const zepto = 1e-21
28export const yocto = 1e-24
29
30const prefixUp = ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
31const prefixDown = ['', 'm', 'μ', 'n', 'p', 'f', 'a', 'z', 'y']
32
33/**
34 * Calculate the metric prefix for a number. Assumes E.g. `prefix(1000) = { n: 1, prefix: 'k' }`
35 *
36 * @param {number} n
37 * @param {number} [baseMultiplier] Multiplier of the base (10^(3*baseMultiplier)). E.g. `convert(time, -3)` if time is already in milli seconds
38 * @return {{n:number,prefix:string}}
39 */
40export const prefix = (n, baseMultiplier = 0) => {
41 const nPow = n === 0 ? 0 : math.log10(n)
42 let mult = 0
43 while (nPow < mult * 3 && baseMultiplier > -8) {
44 baseMultiplier--
45 mult--
46 }
47 while (nPow >= 3 + mult * 3 && baseMultiplier < 8) {
48 baseMultiplier++
49 mult++
50 }
51 const prefix = baseMultiplier < 0 ? prefixDown[-baseMultiplier] : prefixUp[baseMultiplier]
52 return {
53 n: math.round((mult > 0 ? n / math.exp10(mult * 3) : n * math.exp10(mult * -3)) * 1e12) / 1e12,
54 prefix
55 }
56}