convert.js
1.88 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
'use strict';
const lengthConv = new Map([
['in', 96],
['px', 1],
['pt', 4 / 3],
['pc', 16],
]);
const timeConv = new Map([
['s', 1000],
['ms', 1],
]);
const angleConv = new Map([
['turn', 360],
['deg', 1],
]);
/**
* @param {number} number
* @return {string}
*/
function dropLeadingZero(number) {
const value = String(number);
if (number % 1) {
if (value[0] === '0') {
return value.slice(1);
}
if (value[0] === '-' && value[1] === '0') {
return '-' + value.slice(2);
}
}
return value;
}
/**
* @param {number} number
* @param {string} originalUnit
* @param {lengthConv | timeConv | angleConv} conversions
* @return {string}
*/
function transform(number, originalUnit, conversions) {
let conversionUnits = [...conversions.keys()].filter((u) => {
return originalUnit !== u;
});
const base = number * /** @type {number} */ (conversions.get(originalUnit));
return conversionUnits
.map(
(u) =>
dropLeadingZero(base / /** @type {number} */ (conversions.get(u))) + u
)
.reduce((a, b) => (a.length < b.length ? a : b));
}
/**
* @param {number} number
* @param {string} unit
* @param {{time?: boolean, length?: boolean, angle?: boolean}} options
* @return {string}
*/
module.exports = function (number, unit, { time, length, angle }) {
let value = dropLeadingZero(number) + (unit ? unit : '');
let converted;
const lowerCaseUnit = unit.toLowerCase();
if (length !== false && lengthConv.has(lowerCaseUnit)) {
converted = transform(number, lowerCaseUnit, lengthConv);
}
if (time !== false && timeConv.has(lowerCaseUnit)) {
converted = transform(number, lowerCaseUnit, timeConv);
}
if (angle !== false && angleConv.has(lowerCaseUnit)) {
converted = transform(number, lowerCaseUnit, angleConv);
}
if (converted && converted.length < value.length) {
value = converted;
}
return value;
};