Skip to content

Instantly share code, notes, and snippets.

@asynchroza
Created August 31, 2024 20:21
Show Gist options
  • Save asynchroza/daae7003d0ed0f826182cd18bfcc2449 to your computer and use it in GitHub Desktop.
Save asynchroza/daae7003d0ed0f826182cd18bfcc2449 to your computer and use it in GitHub Desktop.
Flyweight example fix
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
}
const isbnNumbers = new Set();
const bookList = [];
const sharedInstances = [];
const addBook = (title, author, isbn, availibility, sales) => {
const bookSharedInstance = createBook(title, author, isbn)
const book = {
sales,
availibility,
isbn,
__proto__: bookSharedInstance
};
bookList.push(book);
return book;
};
const createBook = (title, author, isbn) => {
const book = isbnNumbers.has(isbn);
if (book) {
return getSharedBookInstance(title);
} else {
const book = new Book(title, author, isbn);
isbnNumbers.add(isbn);
sharedInstances.push(book)
return book;
}
};
const getSharedBookInstance = (title) => {
return sharedInstances.filter(book => book.title === title)[0]
}
const getBooks = (title) => {
return bookList.filter(book => book.title === title)
}
addBook("Harry Potter", "JK Rowling", "AB123", false, 100);
addBook("Harry Potter", "JK Rowling", "AB123", true, 50);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", true, 10);
addBook("To Kill a Mockingbird", "Harper Lee", "CD345", false, 20);
addBook("The Great Gatsby", "F. Scott Fitzgerald", "EF567", false, 20);
console.log("Total amount of copies: ", bookList.length);
console.log("Total amount of books: ", isbnNumbers.size);
const harryPotterBooks = getBooks("Harry Potter")
console.log("Books:", harryPotterBooks.length)
const [firstBook, secondBook] = harryPotterBooks
console.log("Are objects equal:", firstBook === secondBook)
console.log("Do they share the same prototype:", Object.getPrototypeOf(firstBook) === Object.getPrototypeOf(secondBook))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment