Skip to content

Commit

Permalink
🐛 Fixed problem with '0' interpolated as empty string
Browse files Browse the repository at this point in the history
  • Loading branch information
vthibault committed Feb 28, 2019
1 parent 062b62e commit 488c292
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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];
Expand Down
33 changes: 31 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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} !',
Expand Down Expand Up @@ -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.');
Expand Down

0 comments on commit 488c292

Please sign in to comment.