Skip to content

Commit

Permalink
Add loose mode
Browse files Browse the repository at this point in the history
  • Loading branch information
sheerun committed Mar 19, 2018
1 parent f3bdc3b commit bb9133d
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
8 changes: 5 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ function parse(al){
});
}

function pick(supportedLanguages, acceptLanguage){
function pick(supportedLanguages, acceptLanguage, options){
options = options || {};

if (!supportedLanguages || !supportedLanguages.length || !acceptLanguage) {
return null;
}
Expand Down Expand Up @@ -58,8 +60,8 @@ function pick(supportedLanguages, acceptLanguage){
var supportedScript = supported[j].script ? supported[j].script.toLowerCase() : supported[j].script;
var supportedRegion = supported[j].region ? supported[j].region.toLowerCase() : supported[j].region;
if (langCode === supportedCode &&
(!langScript || langScript === supportedScript) &&
(!langRegion || langRegion === supportedRegion)) {
(options.loose || !langScript || langScript === supportedScript) &&
(options.loose || !langRegion || langRegion === supportedRegion)) {
return supportedLanguages[j];
}
}
Expand Down
15 changes: 15 additions & 0 deletions tests/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,19 @@ describe('accept-language#pick()', function(){
var result = parser.pick(['en']);
assert.equal(result, null);
});

it('by default should be strict when selecting language', function(){
var result = parser.pick(['en', 'pl'], 'en-US;q=0.6');
assert.equal(result, null);
});

it('can select language loosely with an option', function(){
var result = parser.pick(['en', 'pl'], 'en-US;q=0.6', { loose: true });
assert.equal(result, 'en');
});

it('selects most matching language in loose mode', function(){
var result = parser.pick(['en-US', 'en', 'pl'], 'en-US;q=0.6', { loose: true });
assert.equal(result, 'en-US');
});
});

0 comments on commit bb9133d

Please sign in to comment.