-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcashier.js
75 lines (62 loc) · 2.17 KB
/
cashier.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
const readline = require("readline");
const eventEmitter = require("./eventEmitter.js");
const {Menu} = require("./menu.js");
const {isNaturalNumber, isString} = require('./myUtil.js');
const Order = require("./order.js");
const ORDER_MSG = "주문할 음료를 입력하세요 > ";
const WRONG_ORDER_MSG = "잘못된 주문입니다. ex) 1:2"
const NOT_MENU_NUM = "없는 메뉴 번호 입니다.";
const NOT_MENU_CLASS_ERR = "메뉴 클래스가 아닙니다.";
const checkMenuClass = v => {
if(!(v instanceof Menu))
throw NOT_MENU_CLASS_ERR;
}
class Cashier {
constructor(menu) {
checkMenuClass(menu);
this.orderCount = 1;
this.menu = menu;
}
order(orderText) {
if(!this.isCorrectFormat(orderText))
return eventEmitter.emit('updateScreen', WRONG_ORDER_MSG);
const [num, count] = this.parsing(orderText);
if(!this.menu.hasMenu(num))
return eventEmitter.emit('updateScreen', NOT_MENU_NUM);
const drink = this.menu.getDrink(num);
const order = new Order(this.orderCount++, drink, count);
eventEmitter.emit('newOrder', order);
}
/**
* '숫자:숫자' 포맷을 확인한다.
* @param {string} text
*/
isCorrectFormat(text) {
if(text.length === 0) return false;
if(!this.checkSemicolon(text)) return false;
if(!this.checkNumber(...this.parsing(text))) return false;
return true;
}
/**
* ':' 가 없는지 확인
* ':' 가 가장 첫번째, 끝에 있는지 확인
* ':' 가 2개 이상 있는지 확인
* @param {string} text
*/
checkSemicolon(text) {
const leftIndex = text.indexOf(':');
const rightIndex = text.lastIndexOf(':');
if(leftIndex === -1) return false;
if(leftIndex === 0 || rightIndex === text.length-1) return false;
if(leftIndex !== rightIndex) return false;
return true;
}
checkNumber(...targets) {
if(targets.length === 0) return false;
return targets.every(isNaturalNumber);
}
parsing(text) {
return text.split(':').map(o => parseInt(o));
}
}
module.exports = Cashier;