From bc321640f0c640769dace87694e5eead11f7dc57 Mon Sep 17 00:00:00 2001 From: Marco Schumacher Date: Tue, 21 Sep 2021 15:52:06 +0200 Subject: [PATCH] fix: Don't crash if no "other" case is provided. --- src/translate.ts | 4 +++- test/translator.test.ts | 7 +++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/translate.ts b/src/translate.ts index 19da2a1..93615cd 100644 --- a/src/translate.ts +++ b/src/translate.ts @@ -1,3 +1,4 @@ +import { parse } from '@formatjs/icu-messageformat-parser'; import { IntlMessageFormat } from 'intl-messageformat'; import { mapPotentialArray } from './mapPotentialArray'; import { FlatDict } from './types'; @@ -53,7 +54,8 @@ export function translate({ export function format(template: string, values?: Record, 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); diff --git a/test/translator.test.ts b/test/translator.test.ts index cd2408b..810063f 100644 --- a/test/translator.test.ts +++ b/test/translator.test.ts @@ -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'); +});