I came across a code kata yesterday that had me stumped.
Create a count class that increments when the .incr method is called. It sounded easy, but it was the following caveat that left me scratching my head; the counter must act like a number and support arithmetic operations and comparisons.
Put simply, it meant our counter instance must return the current count as a number when part of an expression.
After a prolonged browse through MDN I came across Object.valueOf , I was aware of it but because I never put it to any practical use it didn’t enter my head. In short Object.valueOf converts an object to a primitive value. All built-in objects inherit and override this method. So the simple solution was to override count.prototype.valueOf with a function that returned the current value of count. A clever use for it.
Here’s a JSbin of the solution.