TypeScript
Borrow
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;
}
Exercise 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.
Show example 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"));
Test yourself
-
What happens to the available field when a book is borrowed?
- set to false
- set to undefined
- stays true
- deleted
Show answer
set to false — 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.
-
Complete the available check
if (book && book.____) {
Show answer
if (book && book.available) {
-
Borrowing parts
- borrowBook
- Borrow a book
- book.available
- Loan status check
- book.available = false
- Mark as borrowed
- lib.books.find(...)
- Find book by id
Next lesson: Return