Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lodash have a one-line method for calling a function if it exists?

Given I have this code:

if (_.isFunction(this.doSomething)) {
    this.doSomething();
}

Whereby loadingComplete is a directive attribute passed in from a parent controller that may not always be provided, is there a cleaner one-line way to call the method if it exists, without repeating the method name?

Something like:

_.call(this, 'doSomething');
like image 773
AgmLauncher Avatar asked Feb 19 '16 13:02

AgmLauncher


2 Answers

_.result(this, 'doSomething', 'defaultValueIfNotFunction')
like image 85
stasovlas Avatar answered Oct 29 '22 13:10

stasovlas


As of version 4.0.0 lodash provides a method called invoke: https://lodash.com/docs/4.15.0#invoke

var object = {
  add: function(a, b) { return a + b }
};

_.invoke(object, 'add', 1, 2);
// => 3

_.invoke(object, 'oops');
// => undefined

Note that it will still explode if for some reason there is something other than a function at the key you provide.

like image 37
Hargo Avatar answered Oct 29 '22 13:10

Hargo