UNPKG

2.72 kBJavaScriptView Raw
1'use strict';
2
3const { typeOf, throwIf } = require('./utils.js');
4const { exactHours, lessLimitAnd30, more30, phrases } = require('./data.js');
5
6const settings = new function Settings() {
7 let _lang = 'ru';
8 let _countDownFrom = 30;
9 let _spellCountDownMinutes = false;
10 let _spellLastMinuteAsWord = true;
11
12 let _spellLastMinuteAsWordIsWarned = false;
13
14 Object.defineProperties(this, {
15 apply: {
16 value: obj => {
17 throwIf.notEnumerableProperty(this, obj);
18 for(const key in obj) {
19 this[key] = obj[key];
20 }
21 },
22 },
23
24 lang: {
25 set: lang => {
26 throwIf.notAllowedLang({ lang });
27 _lang = lang;
28 },
29 get: () => _lang,
30 enumerable: true,
31 },
32 countDownFrom: {
33 set: countDownFrom => {
34 throwIf.notNumberInRange({ countDownFrom }, 0, 60);
35 _countDownFrom = Math.round(countDownFrom);
36 },
37 get: () => _countDownFrom,
38 enumerable: true,
39 },
40 spellCountDownMinutes: {
41 set: spellCountDownMinutes => {
42 throwIf.notBoolean({ spellCountDownMinutes });
43 _spellCountDownMinutes = spellCountDownMinutes;
44 },
45 get: () => _spellCountDownMinutes,
46 enumerable: true,
47 },
48 spellLastMinuteAsWord: {
49 set: spellLastMinuteAsWord => {
50 throwIf.notBoolean({ spellLastMinuteAsWord });
51 if(!_spellLastMinuteAsWordIsWarned && this.spellCountDownMinutes) {
52 console.warn('Note: there is no sence to change "spellLastMinuteAsWord" setting value because "spellCountDownMinutes" is true.');
53 _spellLastMinuteAsWordIsWarned = true;
54 }
55 _spellLastMinuteAsWord = spellLastMinuteAsWord;
56 },
57 get: () => _spellLastMinuteAsWord,
58 enumerable: true,
59 },
60 });
61};
62
63function verbalTime(time = new Date()) {
64 if(typeOf(time) === 'Object') {
65 settings.apply(time);
66 return verbalTime;
67 }
68 throwIf.notDate(time);
69
70 const h = time.getHours();
71 const m = time.getMinutes();
72 const { lang } = settings;
73 const ph = phrases[lang];
74
75 if(m === 0) {
76 return exactHours[lang][h];
77 }
78 if(m === 30) {
79 return `${ph.half} ${lessLimitAnd30[lang][(h+1)%12]}`;
80 }
81 if(m < settings.countDownFrom) {
82 return `${m} ${ph.minute2(m)} ${lessLimitAnd30[lang][(h+1)%12]}`;
83 }
84
85 const m60 = 60-m;
86 if(settings.spellCountDownMinutes) {
87 return `${ph.without} ${m60} ${ph.minute3(m60)} ${more30[lang][h%12]}`;
88 }
89 if(settings.spellLastMinuteAsWord && m60 === 1) {
90 return `${ph.without} ${ph.minute} ${more30[lang][h%12]}`;
91 }
92 return `${ph.without} ${m60} ${more30[lang][h%12]}`;
93}
94
95module.exports = verbalTime;