1
\$\begingroup\$

I have written this code for cookie parsing. Can anyone tell me what optimizations we can do in this or what can we do to make it more concise?

function parseCookies(cookies) {
  var cookie,
    cookieParts,
    parsedCookies = [];

  if (!cookies || !cookies.length) {
    return null;
  }

  // Remove domain from each cookie to decrease the size of cookie (Not needed)
  for (var i = 0; i < cookies.length; i++) {
    cookie = cookies[i];
    cookieParts = cookie.split(';');

    for (var index2 = cookieParts.length - 1; index2 >= 0; index2--) {
      var pair = cookieParts[index2],
        key = pair.split('=')[0];

      if (key && key.trim().toLowerCase() == 'domain') {
        cookieParts.splice(index2, 1);
      }
    }

    cookie = cookieParts.join(';');
    parsedCookies.push(cookie);
  }

  return parsedCookies;
}
\$\endgroup\$
  • \$\begingroup\$ Could you add examples of input and output? As far as I can tell, this isn't so much a parser but rather a sanitizer, since it returns the same format, just with some stuff removed \$\endgroup\$ – Flambino Dec 6 '13 at 18:24
2
\$\begingroup\$

Like I wrote in my comment, the function you've got isn't really a parser. Yes, it parses the strings you pass it, but that's not its purpose, as far as I can tell. Parsing is a byproduct of the actual purpose, which seems to be to sanitize the strings by removing the domain key/value pair.

Now, if you're just looking to remove that key/value pair, you could simply do

function sanitizeCookies(strings) {
  return strings.map(function (cookieString) {
     return cookieString.replace(/\bdomain\s*=[^;]*;?/ig, "");
  });
}

Like @tomdemuyt, I'm using Array.map() so you won't get null back if you pass it an empty array; you'll just get another empty array (and, frankly, that makes more sense, I think).

\$\endgroup\$
1
\$\begingroup\$

This question is a great candidate for using Array.map and Array.filter. That is, if you are willing to return [] instead null if cookies is not provided.

Basically you map cookies to a new array which has modified cookies, and you filter out the value from the cookie that you don't want.

I did not test this, but something like this ought to do the trick:

function parseCookies(cookies) {

  cookies = cookies || [];

  return cookies.map( function(cookie)
  {
     return cookie.split(";").filter( function( value )
    {
      return !( value && value.trim().toLowerCase().substring(0,7) == "domain=" )
    }).join(";");
  });
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.