Varun Upadhyay
Varun Upadhyay

Reputation: 160

How can I store the arguments passed to a function in an array?

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.

Upvotes: 0

Views: 70

Answers (2)

Ollie_W
Ollie_W

Reputation: 337

If you are using an ECMASCRIPT 2015 compiler you could try using (...) rest parameters. They are a proper array of arguments. Otherwise use the keyword "arguments" which is an array like object. It doesn't have all the methods of a proper array you can do loops and .length through it. It stores all the "extra" arguments passed into a function - e.g. those that don't have named parameters

Upvotes: 0

anotherdev
anotherdev

Reputation: 2569

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.

Upvotes: 1

Related Questions