Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

short syntax to call array of functions using lodash

I believe, there is a shorter way (one line) to write this using lodash:

  _.forEach(eventListeners, function(callback) {
    callback(event);
  })

... but can't find yet

like image 350
georgiy.zhuravlev Avatar asked Apr 26 '17 21:04

georgiy.zhuravlev


People also ask

What are Lodash functions?

Lodash is a popular javascript based library which provides 200+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

How can we get values from object using Lodash?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

How do I get the last element of an array using Lodash?

last() method is used to get the last element of the array i.e. (n-1)th element. Parameters: This function accepts single parameter i.e. the array. Return Value: It returns the last element of the array.


1 Answers

Lodash provides a utility function called _.over that returns a function that you can then call to pass some arguments to all of the functions you provided to _.over

Official documentation for _.over

var funs = [
  function(e) { console.log(e) },
  function(e) { console.log(e*2) },
  function(e) { console.log(e*3) }
];

_.over(funs)(10);

This will call all of the functions in the funs array with 10 as their argument, so in this case you should see in your console:

10
20
30

In your case specifically:

_.over(eventListeners)(event);
like image 191
Brennan Avatar answered Oct 25 '22 13:10

Brennan