-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
116 lines (101 loc) · 2.34 KB
/
index.js
File metadata and controls
116 lines (101 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
if (!Array.prototype.flat) {
// Polyfill from https://github.com/jonathantneal/array-flat-polyfill
Object.defineProperty(Array.prototype, 'flat', {
configurable: true,
value: function flat () {
var depth = isNaN(arguments[0]) ? 1 : Number(arguments[0]);
return depth ? Array.prototype.reduce.call(this, function (acc, cur) {
if (Array.isArray(cur)) {
acc.push.apply(acc, flat.call(cur, depth - 1));
} else {
/* istanbul ignore next */
acc.push(cur);
}
return acc;
}, []) : Array.prototype.slice.call(this);
},
writable: true
});
}
const firstExponents = [
{n: 1e3, name: 'thousand'},
{n: 1e6, name: 'million'},
{n: 1e9, name: 'billion'},
{n: 1e12, name: 'trillion'},
{n: 1e15, name: 'quadrillion'},
{n: 1e18, name: 'quintillion'},
{n: 1e21, name: 'sextillion'},
{n: 1e24, name: 'septillion'},
{n: 1e27, name: 'octillion'},
{n: 1e30, name: 'nonillion'},
];
const prefixes = [
'',
'un',
'duo',
'tre',
'quattuor',
'quin',
'sex',
'septen',
'octo',
'novem',
];
const suffixes = [
'decillion',
'vigintillion',
'trigintillion',
'quadragintillion',
'quinquagintillion',
'sexagintillion',
'septuagintillion',
'octogintillion',
'nonagintillion',
'centillion',
];
const exponents = [
{n: 1e100, name: 'googol'},
...firstExponents,
...((suffixes.map((s, i) => prefixes.map((p, j) => ({
n: Number(`1e${firstExponents.length * 3 + (prefixes.length * i + j + 1) * 3}`),
name: p + s,
}))).flat())),
].filter(e => e.n < Infinity)
.sort((a, b) => {
if (a.n > b.n) {
return -1;
} else if (b.n > a.n) {
return 1;
}
/* istanbul ignore next */
return 0;
});
function largenum (n, {
threshold,
max,
exclusions = [],
} = {}) {
const sign = n < 0 ? -1 : 1;
if (sign < 0) {
n = n * -1;
}
if (n < threshold) {
return Number(n).toLocaleString('en-US');
}
let str = '';
const filteredExponents = exponents
.filter(e => !exclusions.some(exclusion => exclusion === e.n));
for (const exponent of filteredExponents) {
if (max && exponent.n > max) {
continue;
}
while (BigInt(n) > BigInt(exponent.n) - BigInt(1)) {
n = Math.round(n / exponent.n);
str = ` ${exponent.name}${str}`;
}
}
return `${sign < 0 ? 'negative ' : ''}${n} ${str.substr(1)}`;
}
module.exports = {
largenum,
};