[JS Practice] Number-like counter(返回数字类型的counter类)

Title :
Number-like counter(返回数字类型的counter类)

You’re going to implement a simple counter class. The counter will start at zero, and every time its incr method is called, it will increase by 1.

There’s one caveat: Your counter must act like a number and support arithmetic operations and comparisons.


For example:

var c = new Counter();
c.incr(); // counter is now at 1
c + 1; // 2
c > 1; // false
c > 0; // true
c == 1; // true
Math.sqrt(c); // 1

You are not required to support equality comparison between two Counter instances.

My solution :

function Counter(){
  this.value = 0;

Counter.prototype.incr = function() {

Counter.prototype.valueOf = function () {
  return this.value;


Ref. from codewars


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s