Way to inject function into chain with underscore

152 views Asked by At

I'm looking for a way to take the contents of the underscore chain and pass it into a function, in this case the chain parses out the timestamp from the file and sorts the array by timestamp, gets the latest one then I'd like to simply reassemble the path with path.format. Is there a way to do this with underscore that I'm simply overlooking?

  return _.chain(dirFiles)
    .filter(function(dirFile){
      return dirFile.match(file.name)
    })
    .map(function(dirFile){
      dirFile = path.parse(dirFile)
      dirFile.timestamp = dirFile.name.split("-")[file.timestampPosition]
      return dirFile
    })
    .sortBy("timestamp")
    .last()
    .inject(path.format)
    .value()
2

There are 2 answers

0
Bergi On BEST ANSWER

No, there is not. However, lodash does provide a _.thru method since v3:

_.thru(value, interceptor, [thisArg])

This method is like _.tap except that it returns the result of interceptor.

You surely can _.mixin it into underscore :-)

0
TaoPR On

_.mixin

Underscore has an option for you to create your own mapping function which maps an object or any kind of data to another object or any kind of data in your own way.

All you need is a definition of your own function

Below is just an example of how to define your function with mixin

_.mixin({
    pathFormat: function(val,interceptor){ 
       // Just an example of how you can pass in your own interceptor
       return interceptor(val) + path.resolve(val); 
    }
});

Then pluck your own function in the chain like this:

_.chain(dirFiles)
   ...
   ...
   sortBy("timestamp")
   .last()
   .pathFormat(path.format)
   .value()

With this, pah.format is an interceptor function you pass in to the pathFormat function you have defined. So you can process an object returned by last() and map it to another resultant object, returns it back to the subsequent chaining function.