Kawd
Kawd

Reputation: 4440

Javascript function that returns two different types of variables depending on input?

I'm trying to follow the rule and avoid repeating the same code.

I have this single function but depending on the input I want it to either return an array of objects or an object (not an array of just one object)

e.g.(the actual function is much longer and more elaborate than this one obviously, there are just the last few lines after a much longer calculation)

function (nameParameter, ageParameter, inputType)
{
  if (inputType === "asObject")
  {
    var x = {};
    x.name = nameParameter;
    x.age = ageParameter;
    return x;
  }
  else if (inputType === "asArray")
  {
    var y = [];
    y.push(nameParameter);
    y.push(ageParameter);
    return y;
  }
};

Is this possible and if so is it good practice? Is there some other way around it?

Otherwise I'll have to create two distinct function with almost the exact same code.

Upvotes: 2

Views: 1183

Answers (4)

SLaks
SLaks

Reputation: 887807

Yes; that will work fine.

Javascript is not strongly-typed; functions can return whatever they want, whenever they want.

Upvotes: 2

Michael Anderson
Michael Anderson

Reputation: 73530

Don't do this. Implement one version and add a wrapper function that converts the the other format you may want. That way the caller always gets consistent behaviour, and theres still no code duplication.

function asObject(nameParameter, ageParameter)
{
    //Lots of work here.
    var x = {};
    x.name = nameParameter;
    x.age = ageParameter;
    return x;
};

function asArray(nameParameter, ageParameter)
{
  //Just defer to the other version and repack its response.
  var o = asObject(nameParameter, ageParameter);
  var y = [o.nameParameter,o.ageParameter ]; 
  return y;
}

Upvotes: 2

paka
paka

Reputation: 1641

if ( typeof inputType == 'object') { 
  //object part of code
} else {
  //array part of code
}

Upvotes: -1

Niccolò Campolungo
Niccolò Campolungo

Reputation: 12052

You can simplify your code by declaring the object and array with the values already set, but in my opinion if you have this strict type of coding it is not necessary to keep this function... Anyway, here is a simplified version:

function (nameParameter, ageParameter, inputType) {
    var ret;
    if (inputType === "asObject") {
        ret = {
            name: nameParameter,
            age: ageParameter
        };
    } else if (inputType === "asArray") {
        ret = [nameParameter, ageParameter];
    }
    return ret;
};

I left it without name and with a semicolon at the end because I guess it has been declared through a variable.

Upvotes: 2

Related Questions