AniUI Academy
medium+250 XPPractice

Encapsulate state with the module pattern

Long before #private fields, the way to protect state was to keep it in a function's scope and return only the operations you wanted to allow. It is still the pattern behind most stores and SDK clients: the internals are unreachable, so every change goes through a method that can validate it.

Implement createAccount(initialBalance = 0). It returns an object with exactly four methods: deposit(amount) adds to the balance and returns the new balance; withdraw(amount) subtracts and returns the new balance; getBalance() returns the current balance; and getHistory() returns the recorded operations. The balance itself must not be an own property of the returned object, so its only own enumerable properties are those four methods. deposit and withdraw throw new Error("Invalid amount") when the amount is not greater than zero, and withdraw throws new Error("Insufficient funds") when the amount exceeds the balance; in both cases the balance is left unchanged and nothing is recorded. getHistory() returns a new array each time, holding one entry per successful operation in order, each of the form { type: "deposit", amount: 10 } or { type: "withdraw", amount: 5 } — mutating the returned array must not affect the account.

What it has to do

  • deposit and withdraw return the new balance and getBalance() agrees with them.
  • The returned object's only own enumerable properties are the four methods.
  • Throw Error("Invalid amount") for an amount that is not greater than zero.
  • Throw Error("Insufficient funds") when a withdrawal exceeds the balance, leaving the balance unchanged.
  • getHistory() returns a fresh array of { type, amount } entries for successful operations only.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.