forked from urfu-2016/javascript-task-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman-time.js
105 lines (83 loc) · 2.41 KB
/
roman-time.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
'use strict';
/**
* @param {String} time – время в формате HH:MM (например, 09:05)
* @returns {String} – время римскими цифрами (IX:V)
*/
function romanTime(time) {
if (checkSpecialChars(time)) {
throw new TypeError('Неверное время');
}
var timeParts = time.split(':');
if (checkTime(timeParts)) {
throw new TypeError('Неверное время');
}
time = getPartsToTime(timeParts);
return time;
}
function getPartsToTime(parts) {
var hours = 'N';
if (parseInt(parts[0]) !== 0) {
hours = romanNumber(parseInt(parts[0]));
}
var minutes = 'N';
if (parseInt(parts[1]) !== 0) {
minutes = romanNumber(parseInt(parts[1]));
}
return hours + ':' + minutes;
}
function romanNumber(number) {
var numberOfDecade = getRomanDecades(number);
var numberOfUnits = getRomanUnits(number % 10);
return numberOfDecade + numberOfUnits;
}
function getRomanDecades(decades) {
var numberOfFifty = parseInt(decades / 50);
var numberOfDecadeRome = '';
for (var i = 0; i < numberOfFifty; i++) {
numberOfDecadeRome += 'L';
}
var moduloOfFifty = decades % 50;
var numberOfDecade = 0;
if (moduloOfFifty > 39 && moduloOfFifty < 50) {
numberOfDecadeRome += 'XL';
} else {
numberOfDecade = parseInt(moduloOfFifty / 10);
}
for (var k = 0; k < numberOfDecade; k++) {
numberOfDecadeRome += 'X';
}
return numberOfDecadeRome;
}
function getRomanUnits(units) {
var moduloOfFive = 0;
var romanNumberUnits = '';
switch (units) {
case 9:
romanNumberUnits = 'IX';
break;
case 4:
romanNumberUnits = 'IV';
break;
default:
if (units > 4) {
romanNumberUnits = 'V';
moduloOfFive = units - 5;
} else {
moduloOfFive = units;
}
}
for (var j = 0; j < moduloOfFive; j++) {
romanNumberUnits += 'I';
}
return romanNumberUnits;
}
function checkTime(timeParts) {
var isHour = parseInt(timeParts[0]) > 23;
var isMinute = parseInt(timeParts[1]) > 59;
return (isHour || isMinute);
}
function checkSpecialChars(time) {
return (time === null || time === undefined || time.length !== 5 ||
time.search(/\d{2}:\d{2}/) < 0);
}
module.exports = romanTime;