JavaScript Practice Object Interaction Checking Out and Returning a Book Demo: Charging Fines to Patrons

James Crosslin
James Crosslin
3,335 Points

My chargeFines solution took a more long term view of fines. I used a setInterval to automatically charge Patrons

This took quite a lot of independent searching around to learn .bind(), and I'm pretty proud of it. I managed to contain this auto-running daily charge within the object, so as soon as it is created, and without the need of any outside chargeFines call, the countdown starts. This solves the problem of having to match back dates and then charge based on a comparison, as it checks daily on its own and automatically fines patrons.

Let me know what you think and what you would've done differently!

class Library {
  constructor(name) { = name
    this.books = []
    this.patrons = []

// binding 'this' to my 'this.chargeFines' was very important, because the asynchronous 
// 'setInterval' method would cause 'this' to reference 'window' when the scope changes
    this._autoCharge = setInterval(this.chargeFines.bind(this), 8.64e7)

    this._dailyFine = 0.1
  addBook(Book) {

  addPatron(Patron) {

  chargeFines() {
    const today = new Date()
    for (let i = 0; i < this.books.length; i++) {
      if (this.books[i].patron && this.books[i].dueDate < today) {
        this.books[i].patron.balance += this._dailyFine
    return "Successful auto-charge cycle complete."