Untitled
unknown
javascript
a year ago
1.6 kB
7
Indexable
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
toString() {
return `Title: ${this.title}, Author: ${this.author}, Year: ${this.year}`;
}
}
class BookLibrary {
constructor() {
this.books = new Map();
}
addBook(title, author, year) {
const key = this.generateKey(title, author);
if (this.books.has(key)) {
throw new Error('Book already exists in library.');
}
this.books.set(key, new Book(title, author, year))
}
findBooks({ title, author }) {
return this.toArray().filter(book => {
const titleMatches = !title
|| book.title.toLowerCase().includes(title.toLowerCase());
const authorMatches = !author
|| book.author.toLowerCase().includes(author.toLowerCase());
return titleMatches && authorMatches;
});
}
findByTitle(title) {
return this.findBooks({ title });
}
findByAuthor(author) {
return this.findBooks({ author });
}
listAllBooks() {
const array = this.toArray();
if (!array.length) {
console.log('No books available.');
} else {
array.forEach(book => console.log(book.toString()));
}
}
toArray() {
return Array.from(this.books.values());
}
generateKey(title, author) {
return `${author.toLowerCase()}-${title.toLowerCase()}`;
}
}Editor is loading...
Leave a Comment