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

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

Description:
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.

要求创建一个counter类,和它的一个成员方法incr,当counter的实例每次调用incr时,它的值都会加1.

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() {
  this.value++;
};

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

此练习的重点在于重写javascript中的一个基础方法valueOf,让其直接返回数字类型的值而不是对象本身。

Ref. from codewars

Advertisements

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