From 488c292e4ee67a224b145cc7772710e9101bf4f3 Mon Sep 17 00:00:00 2001 From: = Date: Thu, 28 Feb 2019 12:01:52 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20=20=20Fixed=20problem=20with=20'?= =?UTF-8?q?0'=20interpolated=20as=20empty=20string?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/compiler.js | 5 +++-- test/index.js | 33 +++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/compiler.js b/src/compiler.js index 2a4b55a..598d214 100644 --- a/src/compiler.js +++ b/src/compiler.js @@ -24,7 +24,8 @@ const escapeText = JSON.stringify; // (text) => '"' + text.replace(/(["\\])/g, ' * @param {String} text * @returns {String} */ -const escapeVariable = text => '(p["' + text.trim() + '"]||"")'; +const escapeVariable = text => + '(p["' + text + '"]||(p["' + text + '"]=="0"?0:""))'; /** * Compile the translation to executable optimized function @@ -77,7 +78,7 @@ function generateCode(parts, plural) { if (type === TYPE_TEXT && value) { code = escapeText(value); } else if (type === TYPE_VARIABLE) { - code = escapeVariable(value); + code = escapeVariable(value.trim()); } else if (type === TYPE_EXPRESSION) { const variable = p[2]; const cases = p[3]; diff --git a/test/index.js b/test/index.js index 392b8b6..fdf8a2a 100644 --- a/test/index.js +++ b/test/index.js @@ -110,6 +110,36 @@ describe('t', () => { expect(i18n.t('hello')).to.equal('Hi and !'); }); + it('interpolates with empty string if null or undefined', () => { + i18n.set('en', { + hello: 'Hi {name} !', + }); + + expect( + i18n.t('hello', { + name: null, + }) + ).to.equal('Hi !'); + + expect( + i18n.t('hello', { + name: undefined, + }) + ).to.equal('Hi !'); + }); + + it('interpolates with 0 if string equal 0', () => { + i18n.set('en', { + msgs: '{count} message(s)', + }); + + expect( + i18n.t('msgs', { + count: 0, + }) + ).to.equal('0 message(s)'); + }); + it('interpolates the same placeholder multiple times', () => { i18n.set('en', { hello: 'Hi {name} and {name} !', @@ -153,8 +183,7 @@ describe('t', () => { it('interpolates select with string and numbers', () => { i18n.set('en', { - number: - 'Test {type,select,1{one} 2{two} other {infinity}}.', + number: 'Test {type,select,1{one} 2{two} other {infinity}}.', }); expect(i18n.t('number', { type: '1' })).to.equal('Test one.');