A clever use for Object.valueOf

A novel use for Object.valueOf

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.

[gist url=“https://gist.github.com/willmcneilly/4ab7bec6183f7bd554d0”]

Here’s a JSbin of the solution.

comments powered by Disqus