Amiga500
Amiga500

Reputation: 6131

Function - Passing the arguments.

I have a large code base, and I am tasked to implement additional functionality. Code is Node.js - Javascript.

There is one function, and it goes like this:

function checkPeople(first, second) {
 if(second) {
   //do some things...
   }
}

That same function is called several times, but generally it is called like:

checkPeople(first);

or...

checkPeople(first, second);

It depends what is being used for. the parameter "first" is always send regardless.

Now I have to add extra functionality to the same function but with the third parameter:

function checkPeople(first, second, third) {
  if(second) {
   //do some things...
   }
  if(third) {
   //do some things
   }
 }

I was thinking to add third parameter to the function, wherever the function is being called (around 2 times), and check for the existance of the parameter inside the function. Which it is already done for the the parameter "second".

Is this approach valid?

Thank you

Upvotes: 0

Views: 57

Answers (2)

DoXicK
DoXicK

Reputation: 4812

I'm going to be making an assumption here, but since the function is called checkPeople i'm going to assume you're doing the same check for every person (for instance: check for every person if he... exists?)

If that is the case:

function checkPeople()
{
    var people = Array.prototype.slice.call(arguments);
    return people.map(function(person) {
        return person == 'eric'; // only eric is a person today
    });
}

Now, you can do this:

var results = checkPerson('eric','peter','james'); // [true, false, false];
var result = checkPerson('eric'); // [true]
var result = checkPerson('james'); // [false]

If there are actually different checks for a first, second, and third parameter, then you indeed still have to implement the if (second) { .. } checks.

Upvotes: 0

alex
alex

Reputation: 5573

If you pass in the argument like this when you call the function, using null as the second argument, it will not call the second. Assuming that is what you are trying to do. checkPeople(first, null, third)

Upvotes: 1

Related Questions