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:
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!