-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1-theory.js
More file actions
97 lines (78 loc) · 1.94 KB
/
1-theory.js
File metadata and controls
97 lines (78 loc) · 1.94 KB
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
'use strict';
// Elements to be visited
class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
accept(visitor) {
visitor.visitProduct(this);
}
inStock() {
return true; // Just a stub
}
}
class Service {
static SUNDAY = 0;
static SATURDAY = 6;
constructor(name) {
this.name = name;
}
accept(visitor) {
visitor.visitService(this);
}
isAvailableAt(date) {
const day = date.getDay();
return day > Service.SUNDAY && day < Service.SATURDAY;
}
}
// Visitors to be acceped
class Purchase {
constructor(items, delivery) {
this.items = [];
this.delivery = null;
for (const item of items) {
this.visitProduct(item);
}
this.visitService(delivery);
}
visitProduct(product) {
const available = product.inStock();
const status = (available ? 'in' : 'out of') + ' stock';
if (available) this.items.push(product);
console.log(`Product "${product.name}" is ${status}`);
}
visitService(service) {
const now = new Date();
const available = service.isAvailableAt(now);
const status = (available ? '' : 'not ') + 'available';
if (available) this.delivery = service;
console.log(`Service "${service.name}" is ${status}`);
}
}
class Inspection {
constructor(items) {
this.items = [...items];
}
check() {
for (const item of this.items) {
this.visitProduct(item);
}
}
visitProduct(product) {
const available = product.inStock();
const status = (available ? 'in' : 'out of') + ' stock';
console.log(`Product "${product.name}" is ${status}`);
}
visitService() {
throw new Error('Not implemented');
}
}
// Usage
const p1 = new Product('Laptop', 1500);
const p2 = new Product('Keyboard', 100);
const delivery = new Service('Delivery');
const electronics = new Purchase([p1, p2], delivery);
console.dir({ electronics });
const inspection = new Inspection([p1, p2]);
inspection.check();