-
Notifications
You must be signed in to change notification settings - Fork 0
/
menuItem.js
102 lines (80 loc) · 2 KB
/
menuItem.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
// const itemSchema = {
// id: 3,
// menuId: 2,
// name: "Tofu",
// description: "Chewy soy",
// price: 9.0
// }
const MENU_ITEMS = []
let itemID = 1;
class MenuItemInvalidError extends Error {
constructor(...params) {
super(...params)
}
}
function validateId(id) {
if (id > 0) return
throw new MenuItemInvalidError('ID must be present')
}
function validateMenuId(id) {
if (id > 0) return
throw new MenuItemInvalidError('ID must be present')
}
function validateName(name) {
if (typeof name === 'string' && name.length >= 3) return
throw new MenuItemInvalidError('Name must be at least 3 characters long')
}
function validatePrice(price) {
if (price >= 0) return
throw new MenuItemInvalidError('Price cannot be negative')
}
function validateMenuItem(vendor) {
validateId(vendor.id)
validateMenuId(vendor.menuId)
validateName(vendor.name)
validatePrice(vendor.price)
}
class MenuItem {
constructor(params) {
this.id = Number.parseInt(params.id)
this.menuId = Number.parseInt(params.menuId)
this.name = params.name
this.description = params.description
this.price = Number.parseFloat(params.price)
}
static all() {
return MENU_ITEMS
}
static create(params) {
let item = new MenuItem(
Object.assign(
params,
{ id: itemID++ }
)
)
validateMenuItem(item)
MENU_ITEMS.push(item)
return item
}
static destroy(id) {
let item = this.find(id)
if (item === undefined) { return undefined }
let index = MENU_ITEMS.indexOf(item)
MENU_ITEMS.splice(index, 1)
return item
}
static destroyAll() {
return MENU_ITEMS.map(x => MENU_ITEMS.shift())
}
static find(id) {
return MENU_ITEMS.find(item => item.id == id)
}
static update(id, params) {
let item = this.find(id)
if (item === undefined) { return undefined }
validateMenuItem(Object.assign({}, item, params))
Object.assign(item, params)
return item
}
}
module.exports = { MenuItem, MenuItemInvalidError }