Use ImmutableJs's update for code reuse
Code reuse in collection pipelines is usually done with a function that has a signature of (coll) => coll
. But unfortunately, these functions do not fit into the flat structure of the pipeline.
Let's see an example!
With a List of log objects, each with a time
, severity
, and a message
, we need to sort them by time and format to a string in multiple places.
const processLogs = (list) => list
.sortBy(({time}) => time)
.map(({time, severity, msg}) => `${severity}[${time}] ${msg}`);
This function takes care of the sorting and the formatting in a central place.
But what happens when we want to insert it into a pipeline?
For example, let's filter by severity and reverse the sort order:
processLogs( // 2nd
logs // input
.filter(({severity}) => severity === "E") // 1st
)
.reverse() // 3rd
The flat structure is gone, and the order of operations is messed up.
The update
function
ImmutableJs provides an update
function that gets a parameter with the signature of (coll) => coll
, which exactly matches the processLogs
above.
update
's purpose is to allow the insertion of custom functions into the pipeline while retaining the flat structure.
logs // input
.filter(({severity}) => severity === "E") // 1st
.update(processLogs) // 2nd
.reverse() // 3rd
Using update
, code can be reused between collection pipelines more easily.