DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

Bookstore Inventory System

Problem:

You are tasked with creating a system to manage books in a bookstore.

The system will store book information (title, author, price, and stock), and it will allow users to check the availability of books,

calculate the total cost of purchasing books, and display books that are in stock.

that is the answer to it :

// Book constructor function

function Book(title, author, price, stock) {

this.title = title;

this.author = author;

this.price = price;

this.stock = stock;

// Method to check availability

this.isAvailable = function () {

return this.stock > 0 ? "In Stock" : "Out of Stock";
Enter fullscreen mode Exit fullscreen mode

};

// Method to purchase books

this.purchaseBooks = function (quantity) {

if (this.stock >= quantity) {

  this.stock -= quantity;

  return `Total cost: $${(this.price * quantity).toFixed(2)}`;

} else {

  return "Not enough stock";

}
Enter fullscreen mode Exit fullscreen mode

};

}

// Create book instances

const book1 = new Book("The Catcher in the Rye", "J.D. Salinger", 10, 5);

const book2 = new Book("To Kill a Mockingbird", "Harper Lee", 12, 2);

const book3 = new Book("1984", "George Orwell", 15, 0);

// Array of book objects

const books = [book1, book2, book3];

// Function to display available books

function displayAvailableBooks(books) {

books.forEach((book) => {

console.log(`${book.title} by ${book.author} - ${book.isAvailable()}`);
Enter fullscreen mode Exit fullscreen mode

});

}

// Call the function to display available books

displayAvailableBooks(books);

// Example purchase

console.log(book1.purchaseBooks(3)); // Purchasing 3 copies of "The Catcher in the Rye"

KEEPCOding #WITHKOtoka

Top comments (0)