Added utils.parseAccepts(str)

This commit is contained in:
TJ Holowaychuk
2011-11-19 21:40:12 -08:00
parent b93629a903
commit fe5efa597b
2 changed files with 74 additions and 0 deletions

View File

@@ -60,6 +60,52 @@ exports.miniMarkdown = function(str){
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2">$1</a>');
};
/**
* Parse accepts `str`, returning an
* object with `.type` and `.quality`.
*
* @param {Type} name
* @return {Type}
* @api public
*/
exports.parseAccepts = function(str){
return str
.split(/ *, */)
.map(type)
.sort(quality);
};
/**
* Parse type `str` returning an
* object with `.type` and `.quality`.
*
* @param {String} str
* @return {Object}
* @api private
*/
function type(str) {
var parts = str.split(/ *; */)
, type = parts[0];
var q = parts[1]
? parseFloat(parts[1].split(/ *= */)[1])
: 1;
return { type: type, quality: q };
}
/**
* Sort by quality.
*
* @api private
*/
function quality(a, b) {
return b.quality - a.quality;
}
/**
* Escape special characters in the given string of html.
*

View File

@@ -28,4 +28,32 @@ describe('utils.escape(html)', function(){
utils.escape('<script>foo & "bar"')
.should.equal('&lt;script&gt;foo &amp; &quot;bar&quot;')
})
})
describe('utils.parseAccepts(str)', function(){
it('should default quality to 1', function(){
utils.parseAccepts('text/html')
.should.eql([{ type: 'text/html', quality: 1 }]);
})
it('should parse qvalues', function(){
utils.parseAccepts('text/html; q=0.5')
.should.eql([{ type: 'text/html', quality: 0.5 }]);
utils.parseAccepts('text/html; q=.2')
.should.eql([{ type: 'text/html', quality: 0.2 }]);
})
it('should work with messed up whitespace', function(){
utils.parseAccepts('text/html ; q = .2')
.should.eql([{ type: 'text/html', quality: 0.2 }]);
})
it('should sort by quality', function(){
var str = 'text/plain;q=.2, application/json, text/html;q=0.5';
var arr = utils.parseAccepts(str);
arr[0].type.should.equal('application/json');
arr[1].type.should.equal('text/html');
arr[2].type.should.equal('text/plain');
})
})