Revisiting custom functions in Jsonata

Because you will have common expressions that may be complex that you need to reuse in multiple places and you only want to define that once and not copy paste it over and over again.

There have been multiple requests for it in the past, so there is some demand. See e.g.:

The difference in my proposal is that instead of creating custom full blown JS functions you are just creating the ability to invoke Jsonata expressions stored in environment variables which is much easier to accomplish.

If you want a use case from what I am trying to do, I have the need to extract a date string like 06/28/2022 from a payload string based on a regex and convert that into either a string like 2022-06 or 2022-06-28 depending on the use case. In what I am doing I will need that conversion in dozens of places.

Here is the Jsonata to do that in one case:

$fromMillis($toMillis($match(payload, /Period Ending:\s+(\d{2}\/\d{2}\/\d{4})/, 1).groups[0],"[M01]/[D01]/[Y0001]"),"[Y0001]-[M01]-[D01]")

I could copy and paste that code over and over again, editing the regex in each case, but imagine instead if I could instead define an environment variable to hide the dirty parts of that and instead I can just invoke this:

$call("getFullDate", payload, /Period Ending:\s+(\d{2}/\d{2}/\d{4})/)

And what I am suggesting does not involve any changes whatsoever to Jsonata, so that doesn't matter. NR currently registers 5 functions to make them callable from Jsonata, e.g. flowContext, which you can see in the: node-red/packages/node_modules/@node-red/util/lib/util.js at master · node-red/node-red · GitHub. My proposal simply adds a 6th one named call.