Hey folks! I’m working on a counter function in JavaScript and I’m stuck. Here’s what I’ve got:
function createTally() {
let total = 0;
function tally() {
return total++;
}
// Need help here
tally.update = (num) => total = num;
tally.subtract = () => total--;
// End of tricky part
return tally;
}
let tally = createTally();
console.log(tally()); // 0
console.log(tally()); // 1
tally.update(10);
console.log(tally()); // 10
tally.subtract();
console.log(tally()); // 10 (not 11)
I’m not happy with how I’m setting the update and subtract methods. Is there a better way to do this? Maybe using prototypes or a different pattern? Any ideas would be awesome! Thanks!
An alternative approach you might consider is using a closure with a revealing module pattern. This maintains privacy for the counter variable while exposing only the necessary methods:
This pattern provides a clean interface, encapsulates the ‘total’ variable, and allows for easy addition of new methods if needed. It’s a flexible solution that maintains good separation of concerns.
I’ve encountered similar challenges with counter functions before. One approach I’ve found effective is using a class-based structure. Here’s how you could refactor your code:
This approach encapsulates all the functionality within a single class, making it more organized and easier to maintain. It also allows for better method naming - ‘count()’ feels more intuitive than using the same name as the class for the main incrementing function.