-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
107 lines (95 loc) · 2.55 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
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
'use strict';
/** Units/Terms data */
const Units = {
// Height/Length/Distance/Range/Depth
centimeter: 'cm',
feet: 'ft',
foot: 'ft',
inch: 'in',
inches: 'in',
kilometer: 'km',
meter: 'm',
mile: 'mi',
millimeter: 'mm',
yard: 'yd',
// Weight
kilogram: 'kg',
gram: 'g',
milligram: 'mg',
ounce: 'oz',
pound: 'lb',
// Volume/Capacity
cup: 'c',
gallon: 'gal',
liter: 'l',
milliliter: 'ml',
pint: 'p',
quart: 'qt',
teaspoon: 'tsp',
// Temperature
calorie: 'cal',
celsius: 'C',
'degrees celsius': 'C',
'degrees centigrade': 'C',
'degrees fahrenheit': 'F',
fahrenheit: 'F',
kilocalorie: 'Cal',
// Speed
knots: 'kn',
'kilometers per hour': 'kph',
'miles per hour': 'mph',
'nautical miles per hour': 'kn'
};
/**
* If the unit is plural convert it to singular form
* @param {string} unit - The unit we are obtaining the abbreviation of
* @returns {string} - The converted unit to singular form
*/
function toSingular(unit) {
if (unit.endsWith('s')) {
return unit.slice(0, -1);
}
return unit;
}
/**
* Check if the original unit was capitalize and capitalize the first letter of the abbreviation
* @param {string} unit - The unit we are obtaining the abbreviation of
* @param {string} abbr - The abbreviation
* @returns {string} - First letter capitalized of the abbreviation
*/
function capitalFirstLetter(unit, abbr) {
if (unit.charAt(0) === unit.charAt(0).toUpperCase()) {
return abbr.charAt(0).toUpperCase() + abbr.substr(1);
}
return abbr;
}
/**
* Tries to retrieve the abbreviation
* @param {string} unit - The unit we are retrieving the abbr. for
* @returns {string} - The abbreviation for the given unit
*/
function getAbbr(unit) {
let abbr = Units[(unit.toLowerCase())];
if(typeof abbr === 'undefined') {
abbr = Units[toSingular((unit.toLowerCase()))];
}
return abbr;
}
/**
* The public abbreviation conversion method
* @param {string} unit - The unit we are obtaining the abbreviation of
* @returns {string} - The abbreviation of the unit if it exists in our Units data
*/
function toAbbreviation(unit) {
if(unit) {
let abbr = getAbbr(unit);
if(typeof abbr !== 'undefined') {
return capitalFirstLetter(unit, abbr);
}
return `No abbreviation found for ${unit}.`;
}
return 'No unit passed';
}
module.exports = toAbbreviation;
// Allow use of default import syntax in TypeScript
module.exports.default = toAbbreviation;