Reputation: 65811
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
Reputation: 9288
this.something = function(which) {
(Array.isArray(which) ? which : [which]).forEach(function(thing) {
doSomething(thing);
});
};
Upvotes: 3
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
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