Skip to content

Commit

Permalink
Add "has" method for checking if keys exist (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
omrilotan authored Jan 2, 2020
1 parent b52fa48 commit bd0da6c
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
16 changes: 16 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,22 @@ class I18n {
) || I18n.getDefault(...keys);
}

/**
* Check if a translation key exists
* @param {string|string[]} keys
* @param {Object} data
* @return {Boolean} [description]
*/
has(keys, data) {
keys = Array.isArray(keys) ? keys : [ keys ];
const alternatives = keys.reduce(
(accumulator, key) => accumulator.concat(this.alternatives(key, data)),
[]
);

return typeof this.find(...alternatives) !== 'undefined';
}

/**
* Create key alternatives with prefixes according to instance scopes
* @param {string} key
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@fiverr/i18n",
"version": "1.7.0",
"version": "1.8.0",
"description": "Translation helper",
"keywords": [
"i18n",
Expand Down
9 changes: 9 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,12 @@ require('@fiverr/i18n/singleton');
// i18n is defined globally
```
### Helper functions
Check if a key is available (including empty strings)
#### has
```js
i18n.has('key');
i18n.has(['key', 'other_key']);
i18n.has('namespace.key');
i18n.has('key', { $scope: 'namespace' });
```
34 changes: 34 additions & 0 deletions tests/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,4 +150,38 @@ describe('I18n', () => {

expect(i18n.translate('i.am.in.scope')).to.equal('I am in scope');
});

it('searches for available keys', () => {
const i18n = new I18n();

i18n.add({
lookup: { key: 'balue', biscuit: '' }
});

[
[ 'lookup.key' ],
[ 'lookup.biscuit' ],
[ ['lookup.pie', 'lookup.key'] ],
[ 'key', { $scope: 'lookup' } ],
[ [ 'pie', 'key' ], { $scope: 'lookup' } ]
].forEach(
(args) => expect(i18n.has(...args), args).to.be.true
);

[
[ 'lookup.pie' ],
[ ['lookup.pie', 'lookup.cake'] ],
[ 'key' ],
[],
[ null ]
].forEach(
(args) => expect(i18n.has(...args), args).to.be.false
);

const child = i18n.spawn('lookup');

expect(child.has('key'), 'child.key').to.be.true;
expect(child.has('biscuit'), 'child.biscuit').to.be.true;
expect(child.has('pie'), 'child.pie').to.be.false;
});
});

0 comments on commit bd0da6c

Please sign in to comment.