cscg24-guacamole

CSCG 2024 Challenge 'Guacamole Mashup'
git clone https://git.sinitax.com/sinitax/cscg24-guacamole
Log | Files | Refs | sfeed.txt

Extensions.js (1774B)


      1
      2var util = require('util');
      3
      4/**
      5 * Module exports.
      6 */
      7
      8exports.parse = parse;
      9exports.format = format;
     10
     11/**
     12 * Parse extensions header value
     13 */
     14
     15function parse(value) {
     16  value = value || '';
     17
     18  var extensions = {};
     19
     20  value.split(',').forEach(function(v) {
     21    var params = v.split(';');
     22    var token = params.shift().trim();
     23
     24    if (extensions[token] === undefined) {
     25      extensions[token] = [];
     26    } else if (!extensions.hasOwnProperty(token)) {
     27      return;
     28    }
     29
     30    var parsedParams = {};
     31
     32    params.forEach(function(param) {
     33      var parts = param.trim().split('=');
     34      var key = parts[0];
     35      var value = parts[1];
     36      if (typeof value === 'undefined') {
     37        value = true;
     38      } else {
     39        // unquote value
     40        if (value[0] === '"') {
     41          value = value.slice(1);
     42        }
     43        if (value[value.length - 1] === '"') {
     44          value = value.slice(0, value.length - 1);
     45        }
     46      }
     47
     48      if (parsedParams[key] === undefined) {
     49        parsedParams[key] = [value];
     50      } else if (parsedParams.hasOwnProperty(key)) {
     51        parsedParams[key].push(value);
     52      }
     53    });
     54
     55    extensions[token].push(parsedParams);
     56  });
     57
     58  return extensions;
     59}
     60
     61/**
     62 * Format extensions header value
     63 */
     64
     65function format(value) {
     66  return Object.keys(value).map(function(token) {
     67    var paramsList = value[token];
     68    if (!util.isArray(paramsList)) {
     69      paramsList = [paramsList];
     70    }
     71    return paramsList.map(function(params) {
     72      return [token].concat(Object.keys(params).map(function(k) {
     73        var p = params[k];
     74        if (!util.isArray(p)) p = [p];
     75        return p.map(function(v) {
     76          return v === true ? k : k + '=' + v;
     77        }).join('; ');
     78      })).join('; ');
     79    }).join(', ');
     80  }).join(', ');
     81}