Skip to content

Commit

Permalink
fix: Don't crash if no "other" case is provided.
Browse files Browse the repository at this point in the history
  • Loading branch information
schummar committed Sep 21, 2021
1 parent a92c0a5 commit bc32164
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/translate.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { parse } from '@formatjs/icu-messageformat-parser';
import { IntlMessageFormat } from 'intl-messageformat';
import { mapPotentialArray } from './mapPotentialArray';
import { FlatDict } from './types';
Expand Down Expand Up @@ -53,7 +54,8 @@ export function translate<F = never>({

export function format(template: string, values?: Record<string, unknown>, locale?: string): string {
try {
const f = new IntlMessageFormat(template, locale);
const ast = parse(template, { requiresOtherClause: false });
const f = new IntlMessageFormat(ast, locale);
const msg = f.format(values);
if (msg instanceof Array) return msg.join(' ');
return String(msg);
Expand Down
7 changes: 7 additions & 0 deletions test/translator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,10 @@ test('locale', async (t) => {
t.is(en.locale, 'en');
t.is(de.locale, 'de');
});

test('plural without other', async (t) => {
const ru = await getTranslator('ru');
t.is(ru.format('{x, plural, one {# one} few {# few} many {# many}}', { x: 1 }), '1 one');
t.is(ru.format('{x, plural, one {# one} few {# few} many {# many}}', { x: 2 }), '2 few');
t.is(ru.format('{x, plural, one {# one} few {# few} many {# many}}', { x: 5 }), '5 many');
});

0 comments on commit bc32164

Please sign in to comment.