TypeScript
Return
Write the book return logic.
The returnBook function
returnBook returns a borrowed book. You find it with find; if the book exists and !available (is borrowed), you set it to true and return true.
function returnBook(lib: Library, bookId: string): boolean {
const book = lib.books.find(b => b.id === bookId);
if (book && !book.available) {
book.available = true;
return true;
}
return false;
}
The return check
When returning, the book must be borrowed; that is, available must be false. We check this with the ! operator.
// Check when returning:
if (book && !book.available) {
book.available = true;
}
Exercise Write the returnBook function
Define Book, Member, Library interfaces. Write addBook and borrowBook functions. Write a function returnBook(lib: Library, bookId: string): boolean: find the book with find, if it exists and !available, set it to true and return true. Add a book, borrow it, try to return 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;
}
function returnBook(lib: Library, bookId: string): boolean {
const book = lib.books.find(b => b.id === bookId);
if (book && !book.available) {
book.available = true;
return true;
}
return false;
}
const lib: Library = { books: [] };
addBook(lib, { id: "b1", title: "TypeScript", author: "Ada", available: true });
borrowBook(lib, "b1");
console.log(returnBook(lib, "b1"));
console.log(returnBook(lib, "b1"));
Test yourself
-
When does returnBook return true?
- When the book cannot be found
- When the book is already on the shelf
- When the book is borrowed
- Always
Show answer
When the book is borrowed — returnBook returns true when the book is found and available is false (borrowed). If the book is already on the shelf or cannot be found, it returns false.
-
Complete the available value
book.available = ____;
Show answer
book.available = true;
-
Returning parts
- returnBook
- Return a book
- !book.available
- Borrowed check
- book.available = true
- Put back on shelf
- return true
- Return successful
Next lesson: Integration