Blogmark
Svelte teaching me about the Web Platform
via jbranchaud@gmail.com
One of the principles behind Svelte is to "Use the Platform". So, I wasn't too surprised while going through the Svelte Tutorial when I encountered a handy, new-to-me feature of the web platform, specifically in the JavaScript part of the platform.
The Multiple Select Bindings tutorial displays a list of ice cream flavors. It would have been easy to miss, but I noticed that as the number of selected flavors changed, the formatting changed.
Two items were separated by an and. More than two items became a comma-separated list with an and separating the last item from the rest. I think it caught my attention because I've implemented some version of this list formatting function numerous times across projects over the years. It also caught my attention because I hadn't noticed a function with the necessary chunk of logic to do that custom formatting.
I scrolled around to see what was responsible for the nice list formatting and found what I should have suspected from the get-go, an Intl
formatter:
<script>
let scoops = $state(1);
let flavours = $state([]);
const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
</script>
<!-- some lines of code elided -->
{:else}
<p>
You ordered {scoops} {scoops === 1 ? 'scoop' : 'scoops'}
of {formatter.format(flavours)}
</p>
{/if}
It's the Intl.ListFormat
object that takes a list of items, some options, and a locale, and is able to nicely format a list as part of a sentence.
I cover this functionality in more detail in my latest TIL, Format a List of Items by Locale.