From fe5efa597b000ef8850a2b8f937d4729328d7ed9 Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Sat, 19 Nov 2011 21:40:12 -0800 Subject: [PATCH] Added utils.parseAccepts(str) --- lib/utils.js | 46 ++++++++++++++++++++++++++++++++++++++++++++++ test/utils.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) diff --git a/lib/utils.js b/lib/utils.js index d4418379..5655452c 100644 --- a/lib/utils.js +++ b/lib/utils.js @@ -60,6 +60,52 @@ exports.miniMarkdown = function(str){ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); }; +/** + * 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. * diff --git a/test/utils.js b/test/utils.js index 4ddb7d5d..c8a2c0a3 100644 --- a/test/utils.js +++ b/test/utils.js @@ -28,4 +28,32 @@ describe('utils.escape(html)', function(){ utils.escape('