3.2 Data Abstractions JS Hack
Hack(s) for intro to data abstractions in JS.
JS Lab: Library
In this lab, similarly to the Python lab, you’ll be working on a simple “database” for a library to understand CRUD operations in relation to representing redundant, similar data under one structure – an abstraction.
For JavaScript, you’ll have to open the web console from Developer Tools (ctrl + shift + p -> Developer: Toggle developer tools).
%%js
// Our "database" is an array of objects, each representing a book in a library.
let library = [
{ title: "1984", author: "George Orwell", checkedOut: false },
{ title: "To Kill a Mockingbird", author: "Harper Lee", checkedOut: true },
{ title: "The Great Gatsby", author: "F. Scott Fitzgerald", checkedOut: false }
];
// Function to display all books
function displayLibrary(lib) {
console.log("\nAll books in the library:");
lib.forEach((book, i) => {
console.log(`Index ${i}:`, book);
});
}
// Function to add a new book
function addBook(lib) {
let title = prompt("Enter book title:");
let author = prompt("Enter author:");
let checkedOut = prompt("Is the book checked out? (yes/no):").toLowerCase() === "yes";
let newBook = { title, author, checkedOut };
lib.push(newBook);
console.log("✅ Book added:", newBook);
}
// Function to find a book by title
function findBook(lib, searchTitle) {
let book = lib.find(b => b.title.toLowerCase() === searchTitle.toLowerCase());
if (book) {
console.log("🔎 Found book:", book);
return book;
} else {
console.log("❌ Book not found.");
return null;
}
}
// Function to update a book's checkedOut status
function updateBook(lib, searchTitle) {
let book = lib.find(b => b.title.toLowerCase() === searchTitle.toLowerCase());
if (book) {
let newStatus = prompt("Is the book checked out? (yes/no):").toLowerCase() === "yes";
book.checkedOut = newStatus;
console.log("✅ Book updated:", book);
} else {
console.log("❌ Book not found.");
}
}
// Function to delete a book
function deleteBook(lib, searchTitle) {
let index = lib.findIndex(b => b.title.toLowerCase() === searchTitle.toLowerCase());
if (index !== -1) {
let removed = lib.splice(index, 1);
console.log("🗑️ Book deleted:", removed[0]);
} else {
console.log("❌ Book not found.");
}
}
// Example usage
displayLibrary(library);
// Uncomment these when running in a browser environment where prompt() works:
// addBook(library);
// findBook(library, "1984");
// updateBook(library, "To Kill a Mockingbird");
// deleteBook(library, "The Great Gatsby");
<IPython.core.display.Javascript object>