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

Given that I have this code:

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

Accordingly, loadComplete is a directive attribute passed from the parent controller that may not always be provided, is there a simpler, single-line way to call a method, if it exists, without repeating the method name?

Sort of:

 _.call(this, 'doSomething'); 
+5
source share
6 answers

_.result(this, 'doSomething', 'defaultValueIfNotFunction')

+9
source

Update

The answer from @stasovlas is the right approach.


Quick and easy

The droid you were looking for:

 _.get(this, 'doSomething', _.noop)() 

It is quite self-documenting, functionally equivalent:

 if (this.doSomething) { this.doSomething(); } else { _.noop(); } 

Better for reuse

If you want to reuse this on your code base, you can use mixin to make it more readable and compressed, and bake it directly in lodash:

 var runIfFunction = function(value) { if (_.isFunction(value)) { return value(); } }; _.mixin({runIfFunction: runIfFunction}); 

What allows you to do this:

 _.runIfFunction(this.doSomething); 
+4
source

Starting with 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 

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

+1
source

This is a little ugly, but you can use result :

 _.result({fn: this.doSomething}, 'fn'); 
0
source

if this.doSomething is either a function or undefined / falsy, then:

 this.doSomething && this.doSomething(); 

is a commonly used pattern.

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

In one line:

 if (_.isFunction(this.doSomething)) this.doSomething(); 
-2
source

Source: https://habr.com/ru/post/1243395/


All Articles