-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
44 lines (35 loc) · 1.3 KB
/
index.js
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
const R = require('ramda');
const formatDecimals = (decimalsCount, value) =>
`${value}${"0".repeat(decimalsCount - value.length)}`;
const formatInteger = (separator, value) => R.compose(
R.join(separator),
R.reverse,
R.map(R.reverse),
R.splitEvery(3),
R.reverse
)(value);
const formatter = (groupingSymbol, separator, decimals) => R.compose(
R.join(separator),
R.filter(value => value),
value => [
formatInteger(groupingSymbol, value.split('.')[0]),
formatDecimals(decimals, value.split('.')[1] || '')
],
R.toString
);
const formatNumber = ((shouldRound, decimals, separator, groupingSymbol, value) => R.compose(
formatter(groupingSymbol, separator, decimals),
value => value / Math.pow(10, decimals),
Math.floor,
accumulator => (value => value + accumulator)(shouldRound ? 0.5 : 0),
value => Math.pow(10, decimals) * value
)(value));
const main = (value, format, shouldRoundValue = true) => {
const regExp = /\d\[(.*)\]\d\[(.*)\](\d*)/;
const matches = format.toString().match(regExp);
if (!matches || value === undefined) return null;
const [thousandSeperator, decimalSeparator, decimals] = matches.slice(1);
const decimalsCount = decimals.length;
return formatNumber(shouldRoundValue, decimalsCount, decimalSeparator, thousandSeperator, value)
}
module.exports = main;