Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript capital letters


May 09, 2021 CoffeeScript


Table of contents


Capital word initials

Problem

You want to convert the initials of each word in the string to capitals.

Solution

Use split-map-stitch mode: first split the string into words, then map to capital the first lowercase letter of the word, and then stitch the converted word into strings.

("foo bar baz".split(' ').map (word) -> word[0].toUpperCase() + word[1..-1].toLowerCase()).join ' '
# => 'Foo Bar Baz'

Or use comprehension to achieve the same result:

(word[0].toUpperCase() + word[1..-1].toLowerCase() for word in "foo   bar   baz".split /\s+/).join ' '
# => 'Foo Bar Baz'

Discuss

Split-map-stitch is a common scripting pattern that can be traced back to the Perl language. It would be more convenient to put this functionality directly into the String class through the Extended Class.

It is important to note that there are two problems with the Split-Map-Stitch mode. T he first problem is that text can only be split effectively if the text form is uniform. I f there are separators in the source string that contain more than one blank character, you need to consider how to filter out extra empty words. One solution is to use regular expressions to match strings of blank characters, rather than matching only one space, as before:

("foo    bar    baz".split(/\s+/).map (word) -> word[0].toUpperCase() + word[1..-1].toLowerCase()).join ' '
# => 'Foo Bar Baz'

But doing so leads to a second problem: in the result string, the original string of blank characters is stitched together to leave only one space.

In general, however, these two issues are acceptable. Therefore, "split-map-stitch" is still an effective technique.