Skip to content

Commit a7eec51

Browse files
author
Oscar Otero
committed
include a basic limited implementation of vsprintf
1 parent f4d51f0 commit a7eec51

File tree

3 files changed

+40
-11
lines changed

3 files changed

+40
-11
lines changed

README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,18 @@ You can add variables to the translations. For example:
4848
translator.gettext('hello :who', {':who': 'world'}); //ola world
4949
```
5050

51-
To use vsprintf, just install one of the available implementations, for example [sprintf](https://github.com/alexei/sprintf.js) and assign the function as the value of `vsprintf` property.
51+
There's also a basic support o sprintf (only `%s` and `%d`)
5252

5353
```js
54-
const sprintf = require('sprintf-js);
54+
translator.gettext('hello %s', 'world'); //ola world
55+
```
5556

56-
translator.vsprintf = sprintf.vsprintf;
57+
To customize the translator formatter, just override the `format` method:
5758

58-
translator.gettext('Hello %s', 'world'); //Hello world
59-
translator.ngettext('One comment', '%s comments', 12, 12); //12 comments
59+
```js
60+
translator.format = function (text, ...args) {
61+
//Your custom format here
62+
}
6063
```
6164

6265
## Short names

package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
"@babel/preset-env": "^7.6.3",
2727
"@babel/register": "^7.6.2",
2828
"mocha": "^6.2.2",
29-
"prettier": "^1.18.2",
30-
"sprintf-js": "^1.0.3"
29+
"prettier": "^1.18.2"
3130
}
3231
}

src/translator.js

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,19 @@ export default class Translator {
116116
return text;
117117
}
118118

119-
if (this.vsprintf) {
120-
return this.vsprintf(text, args);
121-
}
119+
return text.replace(/(%[sd])/g, function(match) {
120+
if (!args.length) {
121+
return match;
122+
}
123+
124+
switch (match) {
125+
case '%s':
126+
return args.shift();
122127

123-
return text;
128+
case '%d':
129+
return parseFloat(args.shift());
130+
}
131+
});
124132
}
125133

126134
translate(domain, context, original) {
@@ -180,3 +188,22 @@ function mergeTranslations(translations, newTranslations) {
180188
}
181189
}
182190
}
191+
192+
function vsprintf(string, args) {
193+
const replace = [].concat(args || []);
194+
195+
return string.replace(/(%[sd])/g, function(match) {
196+
console.log(replace);
197+
if (!replace.length) {
198+
return match;
199+
}
200+
201+
if (match === '%s') {
202+
return replace.shift();
203+
}
204+
205+
if (match === '%d') {
206+
return ParseFloat(replace.shift());
207+
}
208+
});
209+
}

0 commit comments

Comments
 (0)