Name: js-handler/node_modules/restify/node_modules/negotiator/lib/charset.js 
1:
module.exports = preferredCharsets;
2:
preferredCharsets.preferredCharsets = preferredCharsets;
3:
 
4:
function parseAcceptCharset(accept) {
5:
  return accept.split(',').map(function(e) {
6:
    return parseCharset(e.trim());
7:
  }).filter(function(e) {
8:
    return e && e.q > 0;
9:
  });
10:
}
11:
 
12:
function parseCharset(s) {
13:
  var match = s.match(/^\s*(\S+?)\s*(?:;(.*))?$/);
14:
  if (!match) return null;
15:
 
16:
  var charset = match[1];
17:
  var q = 1;
18:
  if (match[2]) {
19:
    var params = match[2].split(';')
20:
    for (var i = 0; i < params.length; i ++) {
21:
      var p = params[i].trim().split('=');
22:
      if (p[0] === 'q') {
23:
        q = parseFloat(p[1]);
24:
        break;
25:
      }
26:
    }
27:
  }
28:
 
29:
  return {
30:
    charset: charset,
31:
    q: q
32:
  };
33:
}
34:
 
35:
function getCharsetPriority(charset, accepted) {
36:
  return (accepted.filter(function(a) {
37:
    return specify(charset, a);
38:
  }).sort(function (a, b) {
39:
    // revsort
40:
    return a.q === b.q ? 0 : a.q > b.q ? -1 : 1;
41:
  })[0] || {q:0}).q;
42:
}
43:
 
44:
function specify(charset, spec) {
45:
  if (spec.charset === '*' || spec.charset === charset) {
46:
    return spec;
47:
  }
48:
};
49:
 
50:
function preferredCharsets(accept, provided) {
51:
  accept = parseAcceptCharset(accept || '');
52:
  if (provided) {
53:
    return provided.map(function(type) {
54:
      return [type, getCharsetPriority(type, accept)];
55:
    }).filter(function(pair) {
56:
      return pair[1] > 0;
57:
    }).sort(function(a, b) {
58:
      // revsort
59:
      return a[1] === b[1] ? 0 : a[1] > b[1] ? -1 : 1;
60:
    }).map(function(pair) {
61:
      return pair[0];
62:
    });
63:
  } else {
64:
    return accept.map(function(type) {
65:
      return type.charset;
66:
    });
67:
  }
68:
}