TypeScript
Integration
Build the working library by combining all parts.
Combine all parts
The library project has four main functions: addBook (add), searchByTitle (search), borrowBook (borrow), returnBook (return). In a session you first add books, then borrow, and finally return.
function addBook(lib: Library, book: Book): void { /* ... */ }
function searchByTitle(lib: Library, title: string): Book[] { /* ... */ }
function borrowBook(lib: Library, bookId: string): boolean { /* ... */ }
function returnBook(lib: Library, bookId: string): boolean { /* ... */ }
Working example
Let's add two books, borrow one, return it, and finally search by title. Borrowing and returning change the available field.
const lib: Library = { books: [] };
addBook(lib, { id: "b1", title: "TypeScript", author: "Ada", available: true });
addBook(lib, { id: "b2", title: "Python", author: "Bob", available: true });
borrowBook(lib, "b1");
returnBook(lib, "b1");
const results = searchByTitle(lib, "Script");
console.log(results.length);
Exercise Write the working library
Define Book, Member, Library interfaces. Write addBook, searchByTitle, borrowBook, returnBook functions. Add two books ("TypeScript", "Python"), borrow one ("b1") and return it, search for "Script" and print the number of matches.
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 searchByTitle(lib: Library, title: string): Book[] {
return lib.books.filter(b => b.title.includes(title));
}
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 });
addBook(lib, { id: "b2", title: "Python", author: "Bob", available: true });
borrowBook(lib, "b1");
returnBook(lib, "b1");
const results = searchByTitle(lib, "Script");
console.log(results.length);
Test yourself
-
What is a sensible flow for a library session?
- Add → borrow → return
- Return → add → borrow
- Borrow → return → add
- Add → return → borrow
Show answer
Add → borrow → return — You first add a book, then borrow it, and finally return it. This order makes a sensible library session.
-
Complete the return call
const result = ____(lib, "b1");
Show answer
const result = returnBook(lib, "b1");
-
Integration flow
- addBook
- First step: add
- borrowBook
- Second step: borrow
- returnBook
- Third step: return
- searchByTitle
- Search tool
Next lesson: Challenge 1: Types