읽음 상태로 표시하기
Coddy JavaScript 여정의 논리 & 흐름 섹션에 포함된 레슨 — 65개 중 46번째.
챌린지
쉬움switch 문에 새로운 케이스 markAsRead를 추가하세요. 이 작업은 도서를 읽음 상태로 표시하고 평점을 추가해야 합니다.
markAsRead 케이스의 경우:
currentData매개변수는 다음을 포함하는 객체입니다:bookId(숫자)rating(1에서 5 사이의 숫자)
- 라이브러리에서 일치하는
id를 가진 도서를 찾으세요. rating이 1에서 5 사이의 숫자인지 확인하세요.- 도서를 찾았고 평점이 유효한 경우:
isRead를true로 설정하세요.rating을 제공된 값으로 설정하세요.
results배열에 적절한 메시지를 추가하세요:- 성공적으로 업데이트된 경우
Book marked as read! - 평점이 유효하지 않은 경우
Invalid rating! Please rate between 1 and 5 - 도서
id가 존재하지 않는 경우Book not found!
- 성공적으로 업데이트된 경우
직접 해보기
// Initialize library data
const libraryData = {
books: [
{
id: 1,
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genre: "Fiction",
isRead: false,
rating: 0,
borrowed: false,
borrowedBy: "",
borrowDate: ""
}
],
readers: [
{
name: "John Smith",
favoriteGenre: "Fiction",
}
]
};
function manageLibrary(actions, data) {
let results = [];
for (let i = 0; i < actions.length; i++) {
const currentAction = actions[i];
const currentData = data[i];
switch (currentAction) {
case 'printBooks':
results.push(libraryData.books);
break;
case 'printReaders':
results.push(libraryData.readers);
break;
case "addBook":
// Add a new book to the library
let newBook = {
id: libraryData.books.length + 1,
title: currentData.title,
author: currentData.author,
year: currentData.year,
genre: currentData.genre,
isRead: false,
rating: 0,
borrowed: false,
borrowedBy: "",
borrowDate: ""
};
libraryData.books.push(newBook);
results.push("Book added successfully!");
break;
case "searchByTitle":
// Search for books by title
let searchResults = [];
for(let i = 0; i < libraryData.books.length; i++) {
if(libraryData.books[i].title.toLowerCase().includes(currentData.toLowerCase())) {
searchResults.push(libraryData.books[i]);
}
}
results.push(searchResults);
break;
case "filterByGenre":
// Filter books by genre
let genreResults = [];
for(let i = 0; i < libraryData.books.length; i++) {
if(libraryData.books[i].genre === currentData) {
genreResults.push(libraryData.books[i]);
}
}
results.push(genreResults);
break;
default:
results.push("Invalid action!");
}
}
return results;
}