Ad

How Can I Store The Arguments Passed To A Function In An Array?

- 1 answer

I am trying to solve the below problem but I am unable to store the values passed by the user to the function in the array. Here is the problem description: In this kata, we're going to help Vicky keep track of the words she's learning.

Write a function, learnWord(word) which is a method of the Robot object. The function should report back whether the word is now stored, or if she already knew the word.

Example:

var vicky = new Robot();
vicky.learnWord('hello') -> 'Thank you for teaching me hello'
vicky.learnWord('abc') -> 'Thank you for teaching me abc'
vicky.learnWord('hello') -> 'I already know the word hello'
vicky.learnWord('wow!') -> 'I do not understand the input'

Here is my code:

function Robot() {

}

Robot.prototype.learnWord = function(word) 
{
  var res;
  var ans=[];
  if(/^[a-zA-Z- ]*$/.test(word) === true)
  {
      if(ans.indexOf(word)===-1)
      {
          ans.push(word);
          res = 'Thank you for teaching me '.concat(word);
          return res;
      }
      else
      {
          res = 'I already know the word '.concat(word);
          return res;
      }
  }
  else
  {
      res='I do not understand the input';
      return res;
  }
}
var vicky = new Robot();

I want that the function should keep in memory the arguments which have already been passed.

Ad

Answer

You have to deplace "ans" and replace calls to 'ans' with 'this.ans'.

function Robot() {
   this.ans = []; 
}

Robot.prototype.learnWord = function(word) 
{
  var res;
  if(/^[a-zA-Z- ]*$/.test(word) === true)
  {
      if(this.ans.indexOf(word)===-1)
      {
          this.ans.push(word);
          res = 'Thank you for teaching me '.concat(word);
          return res;
      }
      else
      {
          res = 'I already know the word '.concat(word);
          return res;
      }
  }
  else
  {
      res='I do not understand the input';
      return res;
  }
}

Each time you do a new Robot(); it will have its own 'ans' variable, and in the prototype you access the 'ans' member of the robot you are using.

Ad
source: stackoverflow.com
Ad