Skip to content
This repository was archived by the owner on Feb 5, 2025. It is now read-only.

Commit bb9133d

Browse files
committed
Add loose mode
1 parent f3bdc3b commit bb9133d

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

index.js

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ function parse(al){
2828
});
2929
}
3030

31-
function pick(supportedLanguages, acceptLanguage){
31+
function pick(supportedLanguages, acceptLanguage, options){
32+
options = options || {};
33+
3234
if (!supportedLanguages || !supportedLanguages.length || !acceptLanguage) {
3335
return null;
3436
}
@@ -58,8 +60,8 @@ function pick(supportedLanguages, acceptLanguage){
5860
var supportedScript = supported[j].script ? supported[j].script.toLowerCase() : supported[j].script;
5961
var supportedRegion = supported[j].region ? supported[j].region.toLowerCase() : supported[j].region;
6062
if (langCode === supportedCode &&
61-
(!langScript || langScript === supportedScript) &&
62-
(!langRegion || langRegion === supportedRegion)) {
63+
(options.loose || !langScript || langScript === supportedScript) &&
64+
(options.loose || !langRegion || langRegion === supportedRegion)) {
6365
return supportedLanguages[j];
6466
}
6567
}

tests/tests.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,19 @@ describe('accept-language#pick()', function(){
144144
var result = parser.pick(['en']);
145145
assert.equal(result, null);
146146
});
147+
148+
it('by default should be strict when selecting language', function(){
149+
var result = parser.pick(['en', 'pl'], 'en-US;q=0.6');
150+
assert.equal(result, null);
151+
});
152+
153+
it('can select language loosely with an option', function(){
154+
var result = parser.pick(['en', 'pl'], 'en-US;q=0.6', { loose: true });
155+
assert.equal(result, 'en');
156+
});
157+
158+
it('selects most matching language in loose mode', function(){
159+
var result = parser.pick(['en-US', 'en', 'pl'], 'en-US;q=0.6', { loose: true });
160+
assert.equal(result, 'en-US');
161+
});
147162
});

0 commit comments

Comments
 (0)