// Part 1: Constructor Functions and Prototype
// Constructor function for Author
function Author(name, birthYear) {
this.name = name;
this.birthYear = birthYear;
}
// Add a method to the Author prototype
Author.prototype.getBio = function() {
return `${this.name} was born in ${this.birthYear}.`;
};
// Constructor function for Book
function Book(title, author, publicationYear) {
this.title = title;
this.author = author; // author should be an instance of Author
this.publicationYear = publicationYear;
}
// Add a method to the Book prototype
Book.prototype.getSummary = function() {
return `${this.title}, written by ${this.author.name}, was published in ${this.publicationYear}.`;
};
// Part 2: Higher-Order Functions
const books = [
new Book("Harry Potter and the Philosopher's Stone", new Author("J.K. Rowling", 1965), 1997),
new Book("1984", new Author("George Orwell", 1903), 1949),
new Book("The Hobbit", new Author("J.R.R. Tolkien", 1892), 1937),
new Book("The Catcher in the Rye", new Author("J.D. Salinger", 1919), 1951)
];
// Higher-order function to filter books by year
function filterBooksByYear(books, year) {
return books.filter(book => book.publicationYear > year);
}
// Part 3: Arrow Functions and IIFEs
// Arrow function to list book titles
const listBookTitles = (books) => books.map(book => book.title);
// IIFE to initialize the system
(function() {
console.log("Initializing Library System...");
books.forEach(book => {
console.log(book.getSummary());
});
})();
// Part 4: Generator Functions
// Generator function to yield books one by one
function* bookGenerator(books) {
for (const book of books) {
yield book;
}
}
// Testing the generator function
const bookGen = bookGenerator(books);
let nextBook = bookGen.next();
while (!nextBook.done) {
console.log(nextBook.value.getSummary());
nextBook = bookGen.next();
}
// Knowledge Testing Summary
console.log("Author Bio:");
console.log(new Author("J.K. Rowling", 1965).getBio()); // J.K. Rowling was born in 1965.
console.log("Filtered Books (published after 1950):");
const filteredBooks = filterBooksByYear(books, 1950);
filteredBooks.forEach(book => console.log(book.getSummary()));
console.log("List of Book Titles:");
console.log(listBookTitles(books));