How to Create a Metro Card System with JavaScript?

Estimated read time 2 min read

A metro card system allows users to purchase tickets for the metro, track their balance, and refill their card balance. Here’s an example of how you could create a simple metro card system in JavaScript:

class MetroCard {
  constructor(balance) {
    this.balance = balance;
  }

  refill(amount) {
    this.balance += amount;
    return `Refilled successfully. New balance: ${this.balance}`;
  }

  purchase(amount) {
    if (this.balance >= amount) {
      this.balance -= amount;
      return `Purchase made successfully. Remaining balance: ${this.balance}`;
    } else {
      return 'Insufficient balance.';
    }
  }
}

// Create a new metro card with an initial balance of $20
let myCard = new MetroCard(20);

// Try making a purchase for $5
console.log(myCard.purchase(5)); // Purchase made successfully. Remaining balance: 15

// Try refilling the card with $10
console.log(myCard.refill(10)); // Refilled successfully. New balance: 25

// Try making a purchase for $30
console.log(myCard.purchase(30)); // Insufficient balance.

In this example, we have a MetroCard class with a constructor method that sets the initial balance of the metro card. The class also has two methods: refill and purchase. The refill method adds an amount to the card balance, and the purchase method subtracts an amount from the balance, if the balance is sufficient. If the balance is insufficient, the purchase method returns an error message.

You can create an instance of the MetroCard class by calling new MetroCard(balance), where balance is the initial balance of the card. You can then use the refill and purchase methods on the instance to update the balance and make purchases.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply