Skip to content

Commit c8e3a34

Browse files
committed
fix(book-library): initialise storage and validate page input
1 parent 8b302b9 commit c8e3a34

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

debugging/book-library/script.js

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,26 @@ window.addEventListener("load", () => {
1414

1515
submitBtn.addEventListener("click", addBook);
1616

17+
// Initialises data and seeds default books if storage is empty
1718
function populateStorage() {
1819
const storedLibrary = localStorage.getItem("myLibrary");
20+
1921
if (storedLibrary) {
20-
myLibrary = JSON.parse(storedLibrary);
22+
const rawData = JSON.parse(storedLibrary);
23+
// Rehydrates plain data back into Book objects
24+
myLibrary = rawData.map(
25+
(data) =>
26+
new Book(data.title, data.author, Number(data.pages), data.check)
27+
);
28+
} else {
29+
// Seeds data for new users
30+
myLibrary = [
31+
new Book("The Hobbit", "J.R.R. Tolkien", 295, false),
32+
new Book("1984", "George Orwell", 328, true),
33+
new Book("Robinson Crusoe", "Daniel Defoe", 252, true),
34+
new Book("The Old Man and the Sea", "Ernest Hemingway", 127, false),
35+
];
36+
saveStorage();
2137
}
2238
}
2339

@@ -32,10 +48,11 @@ function addBook(e) {
3248
// Trims input whitespace to sanitise entries
3349
const title = titleInput.value.trim();
3450
const author = authorInput.value.trim();
35-
const pages = pagesInput.value.trim();
51+
const pages = Number(pagesInput.value);
3652

37-
if (!title || !author || !pages) {
38-
alert("Please fill all fields!");
53+
// Validates input: checks for empty strings, non-numbers, or negative values
54+
if (!title || !author || isNaN(pages) || pages <= 0) {
55+
alert("Please enter valid book details. Pages must be a positive number.");
3956
return;
4057
}
4158
const book = new Book(title, author, pages, readCheckbox.checked);

0 commit comments

Comments
 (0)