Borrow
- TypeScript course
- Beginner
- Lesson 83/89
- 5 min
Write the book borrow logic.
The borrowBook function
borrowBook lends a book. First you find it with find; if the book exists and is available, you set it to false and return true. Otherwise you return false.
function borrowBook(lib: Library, bookId: string): boolean {
const book = lib.books.find(b => b.id === bookId);
if (book && book.available) {
book.available = false;
return true;
}
return false;
}The available check
Before lending a book, check the available field. If it is true, you can lend it; if false, someone has already borrowed it. You combine the two conditions with &&.
// Check before lending:
if (book && book.available) {
book.available = false;
}Practice Write the borrowBook function
Define Book, Member, Library interfaces. Write an addBook function. Write a function borrowBook(lib: Library, bookId: string): boolean: find the book with find, if it exists and is available, set it to false and return true. Add a book, try to borrow it twice, and print the results.
Starter code
// Book, Member, Library arayüzlerini tanımla
// addBook(lib: Library, book: Book): void yaz
// borrowBook(lib: Library, bookId: string): boolean yaz
// kitabı bul, available ise false yap ve true döndür
// bir kitap ekle, iki kez ödünç almayı dene ve yazdırSample solution
interface Book { id: string; title: string; author: string; available: boolean; }
interface Member { id: string; name: string; }
interface Library { books: Book[]; }
function addBook(lib: Library, book: Book): void {
lib.books.push(book);
}
function borrowBook(lib: Library, bookId: string): boolean {
const book = lib.books.find(b => b.id === bookId);
if (book && book.available) {
book.available = false;
return true;
}
return false;
}
const lib: Library = { books: [] };
addBook(lib, { id: "b1", title: "TypeScript", author: "Ada", available: true });
console.log(borrowBook(lib, "b1"));
console.log(borrowBook(lib, "b1"));Expected output
true false
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens to the available field when a book is borrowed?
- set to false Correct answer
- set to undefined
- stays true
- deleted
Explanation: The available field of a borrowed book is set to false. This indicates the book is not on the shelf; the book is not deleted.
2 Complete the available check
if (book && book.____) {
if (book && book.available) {
Explanation: You check whether a book can be lent with book.available. title, author, and id do not relate to loan status.
3 Borrowing parts
| Term | Meaning |
|---|---|
borrowBook |
Borrow a book |
book.available |
Loan status check |
book.available = false |
Mark as borrowed |
lib.books.find(...) |
Find book by id |