Skip to content

DeAndre Boston

How to Write a Simple Book Inventory System In JavaScript

javaScript1 min read

1// Declare the class
2class Books {
3 /* constructor() */
4 //Use a constructor method to set up the template for the object
5 constructor(title, author, ISBN, copies){
6 this.title = title;
7 this.author = author
8 this.ISBN = ISBN
9 this.copies = copies
10 }
11 /*avail()*/
12 //Set up a getter method to run the getAvailability method
13 get avail() {
14 return this.getAvailability();
15 }
16
17 /*getAvailability()*/
18 // This method checks if there are no copies, low on stock, or in stock.
19 getAvailability(){
20 if(this.copies === 0){
21 return 'out of stock'
22 } else if ( this.copies < 10 && this.copies > 0){
23 return 'low stock'
24 }
25 return 'In stock'
26 }
27
28 /*sell()*/
29 /*This method decreases the amount of copies by the number of books sold. You can pass the number of books sold as an
30 argument. It also defaults to 1 if no argument is given */
31 sell(numSold = 1){
32 this.copies -= numSold
33
34 return `${this.copies} left in inventory`
35 }
36
37 /*restock()*/
38 /* This method will increase the amount of copies based the number you pass in as an aarugument. It also defaults
39 to 5 if no argument is given */
40 restock(numCopies = 5){
41 this.copies += numCopies
42 return `You now have ${this.copies} in stock.`
43 }
44
45
46}
47
48/* TEST TEST TEST */
49// Instantiate a new book
50let book1 = new Books('Harry Potter & The Sorcerors Stone', 'JK Rowling', '1234asdf', 20 )
51//Checking to make sure the book is all there.
52console.log(book1)
53//checking to see how many books are avail
54console.log(book1.avail())
55// Testing the sell method
56console.log(book1.sell(5))
57//Restock method
58console.log(book1.restock(20))

Something wrong here? Create an issue

© 2022 by DeAndre Boston. All Rights reserved.