forked from urfu-2016/javascript-task-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
roman-time.js
70 lines (56 loc) · 1.63 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
'use strict';
/**
* @param {String} time – время в формате HH:MM (например, 09:05)
* @returns {String} – время римскими цифрами (IX:V)
*/
var romanUnits = ['N', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'];
var romanTens = ['X', 'XX', 'XXX', 'XL', 'L'];
function arabToRoman(arabNumber) {
if (arabNumber === 0) {
return romanUnits[0];
}
var rom = '';
var dec = Math.floor(arabNumber / 10);
var units = arabNumber % 10;
if (dec > 0) {
rom += romanTens[dec - 1];
}
if (units > 0) {
rom += romanUnits[units];
}
return rom;
}
function parseNumber(number, min, max) {
if (number.length !== 2) {
throw new TypeError();
}
var tens = parseInt(number[0], 10);
var units = parseInt(number[1], 10);
if (isNaN(tens) || isNaN(units)) {
throw new TypeError();
}
var num = tens * 10 + units;
if (num < min || number > max) {
throw new TypeError();
}
return num;
}
function romanTime(time) {
if (typeof time !== 'string') {
throw new TypeError('Неверное время');
}
var hoursAndMinutes = time.split(':');
if (hoursAndMinutes.length !== 2) {
throw new TypeError('Неверное время');
}
var hours = '';
var minutes = '';
try {
hours = parseNumber(hoursAndMinutes[0], 0, 23);
minutes = parseNumber(hoursAndMinutes[1], 0, 59);
} catch (e) {
throw new TypeError('Неверное время');
}
return arabToRoman(hours) + ':' + arabToRoman(minutes);
}
module.exports = romanTime;