Javascript Number add(num)

Description

Javascript Number add(num)


// Adding a method to the Number prototype.

Number.prototype.add = function(num){
  return this + num;
};

var n = 5;/*  w ww .  j a v  a 2s .c  o m*/
assert( n.add(3) == 8, "It works fine if the number is in a variable." );

assert( (5).add(3) == 8, "Also works if a number is wrapping in parentheses." );

// Won't work, causes a syntax error
// assert( 5.add(3) == 8, "Doesn't work, causes error." );

Javascript Number add(num)

/* Prompt//from  ww w  .  ja  v a2s  . c o m
Method chaining is a very interesting way to keep your program clean.

As a part of this Kata, you need to create functions such that one could evaluate the following expression:

(3).add(5).multiply(2)
The above expression evaluates to be 16.

You need to implement the following methods:

add
subtract
multiply
divide
square
After you're done, one could chain these five methods to create chains of almost any length.
*/

// Solution
Number.prototype.add = function (num) {
  return this + num;
};

Number.prototype.subtract = function (num) {
  return this - num;
};

Number.prototype.multiply = function (num) {
  return this * num;
};

Number.prototype.divide = function (num) {
  return this / num;
};

Number.prototype.square = function () {
  return this * this;
};



PreviousNext

Related