3 ms·
He missed an opportunity to make that even shorter and even more of a clusterfuck. I present to you: function compress(data){ var s = {}, q = [];
by chmod775 6y ago
He missed an opportunity to make that even shorter and even more of a clusterfuck.
I present to you:
function compress(data){
var s = {}, q = [];
data.replace(/([^=&]+)=([^&]*)/g, function(m, k, v) {
s[k] ? q[s[k] - 1] += "," + v : s[k] = q.push(m);
});
return q.join("&");
}
- fataliss 6y agoI think he avoided the array + join on purpose and went directly for final string concatenation :)
- recursive 6y agoFurther fucked: function compress(data){ return data.replace(/(?<=(\w+)=[^&]*)&\1=/g,','); } I say: do replace after all! (Javascript didn't have zero-width look-behinds at the time)
- chmod775 6y agoThat doesn't handle strings like foo=1&foo=2&foo=3&blah=a&blah=b&foo=4 correctly. You'd expect foo=1,2,3,4&blah=a,b but get foo=1,2,3&blah=a,b&foo=4 I don't think it's possible to solve this just using a single search/replace.
- recursive 6y agoIt wasn't clear from the post whether that was a valid input. If it is, some parts would need to be re-ordered, making it a very fancy search/replace indeed. But I still think it's possible. One or two replacements to switch the ordering, and then my original one to get the final output.
- recursive 6y agoI put some effort into trying to find a search/replace to do it. Without a high-powered replacement function, I couldn't do it. But I did do this instead. function compress(data){ return data.split`&`.sort().join`&`.replace(/(?<=(\w+)=[^&]*)&\1=/g,','); }
- chmod775 6y agoThat's a really creative way to do it!