OldCurmudgeon
OldCurmudgeon

Reputation: 65811

How to deal with parameter as a value or an array of values

I have several functions of the form:

    this.something = function (which) {
        // One or many.
        if (!Array.isArray(which)) {
            // Normal - just one.
            doSomething(which);
        } else {
            // To all!
            which.forEach(function (thing) {
                // Note the recursion
                something(thing);
            });
        }
    };

Is there a tidier way to do this?

Upvotes: 0

Views: 74

Answers (3)

Walf
Walf

Reputation: 9288

this.something = function(which) {
    (Array.isArray(which) ? which : [which]).forEach(function(thing) {
        doSomething(thing);
    });
};

Upvotes: 3

Josh
Josh

Reputation: 1474

Not sure if this meets the "Tidier" request you're looking for, but you could always handle it in a try/catch.

try {
  which.forEach(function (thing) {
    something(thing);
  });
} catch (e) {
  if (e instanceof TypeError) {
    doSomething(which);
  }
}

Upvotes: 0

user3297291
user3297291

Reputation: 23372

Not really a fan, but you often see this:

// A function that handles values as a single parameter, or inside an array
var doSomething(x) {
  if (Array.isArray(x)) {
    x.forEach(doSomething);
  } else {
    console.log(x);
  }
}

Which you could extract from doSomething and apply in a utility method like so:

var ifArrayForEach = f => x => Array.isArray(x) ? x.forEach(f) : f(x);

var doSomething = x => console.log(x);

var doSomethingArrayOrNot = ifArrayForEach(doSomething);

doSomethingArrayOrNot("Hello world");
doSomethingArrayOrNot(["Hello", "world"]);

Again... I'm not a big fan, but sometimes it can be useful. I'd personally just check before calling. At some point you'll have to know what data you're handling anyway...

Upvotes: 0

Related Questions