Repository navigation
Expand file tree
/
Copy pathBookStoreSolution.js
More file actions
77 lines (61 loc) · 1.74 KB
/
Copy pathBookStoreSolution.js
File metadata and controls
77 lines (61 loc) · 1.74 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
// functional JS version
// function Book(title, author, ISBN, numCopies) {
// this.title = title;
// this.author = author;
// this.ISBN = ISBN;
// this.numCopies = numCopies;
// }
// Book.prototype.getAvailability = function () {
// if (this.numCopies === 0) {
// return 'out of stock';
// } else if (this.numCopies < 10) {
// return 'low stock';
// } else {
// return 'in stock';
// }
// };
// Book.prototype.sell = function (numCopiesSold = 1) {
// this.numCopies -= numCopiesSold;
// };
// Book.prototype.restock = function (numCopiesStocked = 5) {
// this.numCopies += numCopiesStocked;
// };
// const HungerGames = new Book('Hunger games', 'Suzanne Collins', 123456, 45);
// HungerGames.sell(3);
// console.log(HungerGames.numCopies);
// Object oriented version
class Book {
constructor(title, author, ISBN, numCopies) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.numcopies = numCopies;
}
get availability() {
return this.getAvailability();
}
getAvailability() {
if (this.numCopies === 0) {
return 'out of stock';
} else if (this.numCopies < 10) {
return 'low stock';
} else {
return 'in stock';
}
}
sell(numCopiesSold = 1) {
this.numCopies -= numCopiesSold;
return this.numCopies;
}
restock(numCopiesRestocked = 5) {
this.numCopies += numCopiesRestocked;
return this.numCopies;
}
}
const HarryPotter = new Book('Harry Potter', 'J.K. Rowling', 12345, 5);
console.log(HarryPotter.getAvailability());
console.log(' restocking ...');
HarryPotter.restock(1);
console.log('After restocking :', HarryPotter.getAvailability());
HarryPotter.sell(18);
console.log('after selling, we have :', HarryPotter.getAvailability());