📜 ⬆️ ⬇️

Search without replacement, or arrays without arrays

Note: below is the translation of the “Search and Don't Replace” note. In it, the author reflects on the methods of converting a query string to an array in JavaScript with minimal CPU time. My comments further in italics.

A little earlier today, my friend, Marc Grabanski, threw me a question: how to convert the query string of the form foo=1&foo=2&foo=3&blah=a&blah=b to something like foo=1,2,3&blah=a,b most optimal way foo=1,2,3&blah=a,b ? At that time he already had his own decision , and he was curious whether it could be improved in any way.

I thought a little and suggested the following solution:
')
  function compress (data) {
     var q = {}, ret = "";
     data.replace (/ ([^ = &] +) = ([^ &] *) / g, function (m, key, value) {
         q [key] = (q [key]? q [key] + ",": "") + value;
     });
     for (var key in q)
         ret = (ret? ret + "&": "") + key + "=" + q [key];
     return ret;
 } 


read further on webo.in →

Source: https://habr.com/ru/post/31575/


All Articles