5 ms·
I would have come up with something like this: Object.entries(Array.from(new URLSearchParams("foo=1&foo=2&foo=3&blah=a&blah=b").entries()).reduce((a,[k,v]) =>
by Ciantic 6y ago
I would have come up with something like this:
Object.entries(Array.from(new URLSearchParams("foo=1&foo=2&foo=3&blah=a&blah=b").entries()).reduce((a,[k,v]) => ({ ...a, [k]: [...a[k] ?? [], v] }), {})).map(([key, values]) => `${key}=${values.join(",")}`).join("&");
- chrisrhoden 6y agoThings sure have changed in the last 12 years! The only method you're using that existed back then is join. Wild.
- augusto-moura 6y agoIf you read the article he makes a point about not using intermediate arrays and .join()
- Ciantic 6y agoThat's a good point, but my post didn't have any grand point :) I was hoping other people to come up modern solutions to this same original problem. Even my solution is questionable, because it relies on generating new URLSearchParams with strings, if one wants to be secure the reduce should take URLSearchParams as accumulator and add the items there.
- kbenson 6y agoIs creating an array really more costly than altering a string? I think it may depend on how much condensing of params you expect compared to singular params. The things being optimized for also may have changed over the intervening decade. That's the problem with optimizing something without respect for it's intended common workload, or expecting those justifications to hold over time in all cases. Edit: Woah, made a hash of that before going in and fixing all the typos from my phone keyboard.
- ballenf 6y agoI don't think this was posted as "I would submit a PR with this code for prod" but more of a "here's a cool one-liner for fun" approach. I enjoy reading people's off-the-cuff code golf stuff and usually learn something.
- minitech 6y ago> .reduce((a,[k,v]) => ({ ...a, [k]: [...a[k] ?? [], v] }), {})) Note that this unfortunately common pattern is quadratic, which is usually not a good idea, and can have conflicts between entries and properties of Object.prototype. A similar implementation without those problems: .reduce((a, [k, v]) => a.has(k) ? a.set(k, [v]) : (a.get(k).push(v), a), new Map()) And an alternate implementation: const input = new URLSearchParams("foo=1&foo=2&foo=3&blah=a&blah=b"); const result = new URLSearchParams(); for (const key of input.keys()) { if (!result.has(key)) { result.set(key, input.getAll(key).join(",")); } } return String(result);