Functional Programming — The Examples Series — Use Reduce to Create a Formatted String

This is the 7th article in my “examples series” for functional programming. Read about the series here, including links to previous and future examples.

I had a need to create a particularly formatted string that is in the form: <label>, pipe symbol (|), <guid>. These are called label/guid pairs and if there are more than one, I needed to separate these pairs with a semicolon.

Here’s the code that does that and you can see the formatted string that I require in the comments:

Get me some pairs

A JavaScript function (written in TypeScript) called GetGuidLabelPairs is passed in an array of strings representing labels and a “termLabel.” I know it’s a little confusing, but “termLabel” is simply a pointer to an object from which I can retrieve Guids. A separate boring function, GetTaxonomyFieldValue, uses this termLabel field to get the Guid.

The function uses the reduce method on the labels array and works as follows:

  • Iterate over the labels array
  • Invoke a function (implemented in TypeScript here as a lambda) for each entry in the labels array.
  • Pass that function: pairAsBuilt and currentLabel. “pairAsBuilt” is the result of the previous call to the function. “pairAsBuilt” is initialized to a blank string (that’s accomplished with the lonely final parameter on the reduce call dangling at the end). “currentLabel” is the current label from “labels” array and is always passed into the reduce function per iteration over the array. (I’m not sure how to word this better!)
  • The lambda function concatenates the guid that GetTaxonomyFieldValue() returns to the current value of “pairsAsBuilt”. It uses the ternary operator to insert a semicolon between pairs (no semicolon required if “pairsAsBuilt” is blank, which it will be in the first iteration).

This is exactly what reduce is for. It iterates over a collection and “reduces” the collection down to a single value.

Hope this helps!


One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.