-
Notifications
You must be signed in to change notification settings - Fork 0
/
menu.js
90 lines (70 loc) · 1.65 KB
/
menu.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
// const menuSchema = {
// id: 2,
// name: "Bar",
// vendorId: 1
// }
const MENUS = []
let menuID = 1;
class MenuInvalidError extends Error {
constructor(...params) {
super(...params)
}
}
function validateId(id) {
if (id > 0) return
throw new MenuInvalidError('ID must be present')
}
function validateName(name) {
if (typeof name === 'string' && name.length >= 3) return
throw new MenuInvalidError('Name must be at least 3 characters long')
}
function validateVendorId(id) {
if (id > 0) return
throw new MenuInvalidError('Vendor ID must be present')
}
function validateMenu(menu) {
validateId(menu.id)
validateName(menu.name)
validateVendorId(menu.vendorId)
}
class Menu {
constructor(params) {
this.id = Number.parseInt(params.id)
this.name = params.name
this.vendorId = Number.parseInt(params.vendorId)
}
static all() {
return MENUS
}
static create(params) {
let menu = new Menu({
name: params.name,
vendorId: params.vendorId,
id: menuID++
})
validateMenu(menu)
MENUS.push(menu)
return menu
}
static destroy(id) {
let menu = this.find(id)
if (menu === undefined) { return undefined }
let index = MENUS.indexOf(menu)
MENUS.splice(index, 1)
return menu
}
static destroyAll() {
return MENUS.map(x => MENUS.shift())
}
static find(id) {
return MENUS.find(menu => menu.id == id)
}
static update(id, params) {
let menu = this.find(id)
if (menu === undefined) { return undefined }
validateMenu(Object.assign({}, menu, params))
Object.assign(menu, params)
return menu
}
}
module.exports = { Menu, MenuInvalidError }