Skip to content

Commit

Permalink
Fix default locale fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
eartharoid committed Oct 7, 2021
1 parent 4722a34 commit afa5de3
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 20 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@eartharoid/i18n",
"version": "1.0.0",
"version": "1.0.1",
"description": "Simple and lightweight message localisation",
"main": "dist/index.js",
"types": "types.d.ts",
Expand Down
27 changes: 10 additions & 17 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,20 +86,14 @@ module.exports = class I18n {
message: string,
...args: MessageArgs
): string | undefined {
if (!this.locales.includes(locale))
throw new Error(`A locale with the name of "${locale}" does not exist`);
if (!this.locales.includes(locale)) throw new Error(`A locale with the name of "${locale}" does not exist`);

let text;

try {
text = this.resolve(this.messages[locale], message);
} catch (e) {
throw new Error(`"${message}" does not exist in the "${locale}" locale`);
}
let text = this.resolve(this.messages[locale], message) ?? this.resolve(this.messages[this.default_locale], message);

if (!text) return undefined;

if (!args) return text;
if (!args && typeof text === 'string') return text;
else if (!args) throw new Error(`"${message}" is an array and a number was not provided.`);

if (text instanceof Array) {
const number = args.shift();
Expand All @@ -119,17 +113,16 @@ module.exports = class I18n {

if (typeof args[0] === 'object') {
const regex = /(?<!\\){{1,2}\s?([A-Za-z0-9\-._:]+)\s?(?<!\\)}{1,2}/gi;
const data: NamedArgs = args[0];
return text
.replace(regex, ($, $1) => {
const value = this.resolve(data, $1);
return value === undefined ? $ : value;
});
const data: NamedArgs = args[0];
return text.replace(regex, ($: string, $1: string): string | undefined => {
const value = <string>this.resolve(data, $1);
return value === undefined ? $ : value;
});
} else {
const regex = /(?<!\\)%(d|s)/gi;
let i = 0;
return text
.replace(regex, () => args[i++]);
.replace(regex, () => <string>args[i++]);
}
}

Expand Down
3 changes: 2 additions & 1 deletion test/locales/original.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
"You own a single {vehicles.type}",
"You own {vehicles.count} {vehicles.type}s"
]
}
},
"english_only": "Hello"
}
8 changes: 7 additions & 1 deletion test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,10 @@ test('plural vehicles 3', t => {
}
});
t.is(actual, expected);
});
});

test('missing translation', t => {
const expected = 'Hello';
const actual = i18n.getMessage('translated', 'english_only');
t.is(actual, expected);
});

0 comments on commit afa5de3

Please sign in to comment.