Tom Söderlund
Tom Söderlund

Reputation: 4747

How to apply a function to object OR array of similar objects

input below can be either a singular Object, or an Array of same type of Objects. I want to apply myFunction to all those Objects in any case.

I do it like this with Lodash:

if (input.length !== undefined) {
    // Array
    return _.map(input, myFunction.bind(this, options));
}
else {
    // One object
    return myFunction(options, input);
}

Is there a better way?

Upvotes: 1

Views: 41

Answers (1)

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

An interesting approach for you is using spread syntax, so you would always receive an array in your function, simplifying it:

function f1(...input) {
  return _.map(input, myFunction.bind(this, options)); 
}

...

f1(o1); // call passing a single object 
f1(o1, o2); // call passing two objects 
f1(...[o1, o2]); // call passing an array with two objects

Upvotes: 1

Related Questions