Skip to content

Commit

Permalink
Format count and ordinal as number (#181)
Browse files Browse the repository at this point in the history
* Format count cardinalization as number

* Format count ordinalization as number

* changeset
  • Loading branch information
ryanwilsonperkin authored Sep 13, 2023
1 parent 00a310d commit f5326a4
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/five-trees-sell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/i18next-shopify': patch
---

Supports formatting of count and ordinal values as numbers
12 changes: 11 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,20 @@ class ShopifyFormat {
let interpolated = res;
matches.forEach((match) => {
const interpolation_key = match.replace(MUSTACHE_FORMAT, '$1');
const value =

let value =
interpolation_key === 'ordinal'
? options.count || options.ordinal
: options[interpolation_key];

// Cardinal and Ordinal pluralizations should be formatted according to their locale
// eg. "1,234,567th" instead of "1234567th"
if (interpolation_key === 'ordinal' || interpolation_key === 'count') {
value = new Intl.NumberFormat(this.i18next.resolvedLanguage).format(
value,
);
}

interpolated = utils.replaceValue(interpolated, match, value ?? '');
});
return interpolated;
Expand Down
12 changes: 12 additions & 0 deletions test/shopify_format.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,12 @@ describe('shopify format', () => {
);
});

it('formats cardinal pluralization according to locale format', () => {
expect(i18next.t('cardinal_pluralization', {count: 5000})).toBe(
'I have 5,000 cars.',
);
});

it('falls back to the `other` key if the proper cardinal pluralization key is missing', () => {
expect(
// A count of 1 in `en` should use the `one` key, but it's missing.
Expand Down Expand Up @@ -240,6 +246,12 @@ describe('shopify format', () => {
).toBe('This is my 4th car');
});

it('formats ordinal pluralization according to locale format', () => {
expect(
i18next.t('ordinal_pluralization', {count: 5000, ordinal: true}),
).toBe('This is my 5,000th car');
});

it('handles ordinal pluralization lookups (using ordinal: <number>)', () => {
expect(i18next.t('ordinal_pluralization', {ordinal: 1})).toBe(
'This is my 1st car',
Expand Down

0 comments on commit f5326a4

Please sign in to comment.