User Story
Feature: Book Rating system
As an avid reader, Avika would like to understand which book she should read next and which are worth her time, so a book rating system would allow her to browse through other people’s opinions on books so that if she finds a book with a good rating, she can use that for her next big read! She would also be able to provide her own opinion on books, like rating the book, liking, commenting on it, and replying to other’s comments.
Program with Output
In the random_book() function, the jsonify() function is used to send the output in the form of a JSON response. This response includes the book’s title, author, genre, description, and image_cover as output, which is then displayed on the frontend. The jsonify() function helps format the response that is returned when the random book data is fetched.
return jsonify({
'title': book[1],
'author': book[2],
'genre': book[3],
'description': book[4],
'image_cover': book[5]
})
Program with Input and Output
On the frontend, when the user submits a comment using the textarea input field, the addComment() function in JavaScript processes the user’s input. The user’s input is then displayed as part of the output in the form of added comments that are stored in the comments object. This creates a cycle where user input directly affects the displayed content.
const commentText = commentInput.value.trim();
comments[currentBook.title].push(comment);
saveComments();
displayComments();
Program with a List
In the comments object in JavaScript, each book title has an associated list of comments. When the user submits a new comment, it is added to this list for the relevant book. This list allows multiple comments to be stored for each book and dynamically displayed on the page.
comments[currentBook.title] = [];
comments[currentBook.title].push(comment);
Program with a Dictionary
The bookRatings object in JavaScript is a dictionary where each key is a book title, and its value is the book’s rating. This dictionary allows easy lookup and modification of the rating for each book. When a user rates a book, the rating is updated in this dictionary.
const bookRatings = {
"Harry Potter and the Sorcerer's Stone": 4.8,
"Percy Jackson & the Olympians: The Lightning Thief": 4.3,
"The Hunger Games": 4.2
};
Program with Iteration
In the displayComments() function, the forEach() method is used to iterate over the list of comments for the current book. This iteration dynamically creates a comment box for each item in the list and displays it on the page. This allows for the number of comments to increase without additional code.
bookComments.forEach((comment, index) => {
const commentDiv = document.createElement('div');
commentDiv.classList.add('comment-box');
commentDiv.innerHTML = `
<div class="comment-text">
<strong>${comment.username}</strong><br>${comment.text}
</div>
`;
commentsList.appendChild(commentDiv);
});
Program with a Function to Perform Mathematical and/or Statistical Calculations
This function updates the rating of a book based on user input. The rating is recalculated by taking the average of the current rating and the new rating. The currentLikes variable tracks how many ratings the book has received and is updated each time a rating is given.
function rateBook(rating) {
const bookTitle = currentBook.title;
// Update the book rating using a more accurate average calculation
bookRatings[bookTitle] = (bookRatings[bookTitle] * currentLikes + rating) / (currentLikes + 1);
currentLikes++;
document.querySelectorAll('.rating-stars span').forEach((star, index) => {
star.style.color = index < rating ? 'yellow' : 'gray';
});
saveComments();
}
Program with a Selection/Condition
This function uses an if-else statement to toggle the “like” status of a book. If the user has already liked the book, the function unlikes it; otherwise, it likes the book. It also updates the number of likes and stores the information in backend.
function toggleLike() {
if (liked) {
liked = false;
currentLikes--;
document.getElementById('heart').textContent = '♡';
} else {
liked = true;
currentLikes++;
document.getElementById('heart').textContent = '❤️';
}
document.getElementById('likeButton').textContent = `Like (${currentLikes})`;
likesCount[currentBook.title] = currentLikes;
localStorage.setItem('likes', JSON.stringify(likesCount));
}
Program with Purpose
This function serves the purpose of fetching a random book from the backend API. It handles the response and displays book information, such as the title, author, genre, and description, on the webpage. If there is an issue, it alerts the user and logs the error.
function fetchRandomBook() {
fetch(`${PythonURI}/api/random_book`)
.then(response => response.json())
.then(data => {
if (data && data.title) {
currentBook = data;
const bookTitle = data.title;
const bookAuthor = data.author || 'Unknown Author';
const bookGenre = data.genre || 'Unknown Genre';
const bookDescription = data.description || 'No description available';
const coverUrl = data.image_cover || 'default-image.jpg';
displayBookInfo(bookTitle, bookAuthor, bookGenre, bookDescription, coverUrl);
} else {
alert('No book data found.');
}
})
.catch(error => {
console.error('Error fetching book data:', error);
alert('Failed to fetch book information.');
});
}