-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathindex.js
More file actions
115 lines (98 loc) · 2.27 KB
/
index.js
File metadata and controls
115 lines (98 loc) · 2.27 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
/**
* Non-Breaking Space ` `
* @const {string}
*/
const NBSP = String.fromCharCode(160);
/**
* @typedef {Object} ParsedNumber
* @prop {string} integer
* @prop {string} fraction
* @prop {string} sign
*/
/**
* @param {number} number
* @returns {ParsedNumber}
*/
function parseNumber(number) {
const isNegative = number < 0;
let numberString = String(number);
if (isNegative) {
numberString = numberString.slice(1);
}
const decimal = numberString.split('.');
return {
integer: decimal[0],
fraction: decimal[1] || '',
sign: isNegative ? '-' : ''
};
}
/**
* @param {number} number
* @param {string} separator
* @returns {string}
*/
function format(number, separator) {
number = String(number);
while (number.length % 3) {
number = '#' + number;
}
let result = number.substr(0, 3);
result = result.replace(/#/g, '');
let i;
const {length} = number;
for (i = 3; i < length; i += 3) {
result = result + separator + number.substr(i, 3);
}
return result;
}
/**
* @param {number} number
* @param {Object|string} [options=" "]
* @param {string} [options.separator=" "]
* @param {boolean} [options.formatFourDigits=true]
* @returns {string}
*
* @example
* formatThousands(1000);
* //=> '1 000'
*
* formatThousands(5000, {formatFourDigits: false});
* //=> '5000'
*
* formatThousands(10000, {separator: "'"});
* //=> "10'000"
*/
module.exports = function (number, options) {
let result = '';
let separator = NBSP;
let formatFourDigits = true;
if (!number && number !== 0) {
return result;
}
const numberObject = parseNumber(number);
const numberString = String(number);
if (typeof options === 'object') {
if (options.separator) {
({separator} = options);
}
if (typeof options.formatFourDigits === 'boolean') {
({formatFourDigits} = options);
}
} else if (typeof options !== 'undefined') {
separator = options;
}
if (
numberObject.integer.length <= 3 ||
(numberObject.integer.length === 4 && !formatFourDigits)
) {
result = numberString;
} else {
result += numberObject.sign;
result += format(numberObject.integer, separator);
if (numberObject.fraction) {
result += '.';
result += numberObject.fraction;
}
}
return result;
};