I recently came across a problem of rendering an array of strings as a human readable string in the format: “A, B and C”. It didn’t seem too difficult at first but I decided to do this in a more functional way, without using a loop. Additionaly it needed to work with arrays of single element and even an empty array.
The cases are:
… and so on
First let’s look at a naive solution with a loop. This can be improved and optimized, but I was not interested in such a solution, so I din’t explore it further.
That is such mess, lets change that:
Now, that looks organized. Still, if somehow we can include the cases for array length being 0, 1 or 2 in the default logic, we would have a nicer solution.
Is there a better solution? I am still looking.
Update: Ok, so one of my friends suggested a solution, by joining the array and replacing the last comma as with ‘and’. I must admit that the solution has a beauty of its own.
I am not sure if the regex used is the best possible, but it works. The disadvantage of this solution is that it cannot be extended to create strings such as ‘A, B, C and 4 others’, while the previous solution can be,
Another disadvantage, it is not as much fun as the previous one ☺.