Serialise params into a query string
The reverse trip matters more than it looks: if the same set of filters can produce two different strings, your cache keys, your analytics and your React Query keys all fragment. Sorting the keys makes the output canonical.
Implement stringifyQuery(params) returning the query string **without** a leading ?. Take the object's own keys, sort them ascending with the default Array.prototype.sort comparison, and process them in that order.
Skip any entry whose value is null or undefined. An empty string is kept and renders as key=. Booleans render as true and false, numbers with String(value). An array value produces one key=value pair per element in array order, all sitting at that key's sorted position; an empty array produces nothing at all.
Encode both key and value with encodeURIComponent, join the pairs with &, and return "" when there is nothing to emit.
Arguments
paramsRecord<string, string | number | boolean | Array | null | undefined>- The params object. Values may be primitives or arrays;
nullandundefinedvalues are omitted.
Returns
string — A URL query string without a leading ?, with keys sorted ascending so the result is canonical. "" for an empty object.
Examples
stringifyQuery({ sort: "name", page: 2 });
// => "page=2&sort=name"Keys are sorted so the output is stable across calls.
stringifyQuery({ tag: ["a", "b"], q: "hello world" });
// => "q=hello%20world&tag=a&tag=b"Arrays expand into one pair per element; values are percent-encoded.
stringifyQuery({ a: null, b: undefined, c: "", d: false });
// => "c=&d=false"null/undefined drop; "" stays as key=; booleans stringify.
What it has to do
- Sort keys ascending with the default sort so the output is canonical.
- Skip
nullandundefinedvalues but keep""askey=. - Expand an array value into one pair per element, in array order; emit nothing for an empty array.
- Encode keys and values with
encodeURIComponentand join pairs with&. - Return the string without a leading
?, and""when empty.
Notes
- Canonicalising with a sort is what lets you use the query string as a cache key:
{ a: 1, b: 2 }and{ b: 2, a: 1 }both serialise identically. encodeURIComponentleaves!'()*unencoded, which is fine for URLs but can trip up strict RFC 3986 consumers. For those you can replace them manually after calling.
Stuck? The javascript course covers everything this challenge needs.
- 1.sorts keys and stringifies numbers
- 2.expands arrays and encodes values
- 3.skips null and undefined but keeps empty strings and false
- 4.encodes the key and drops an empty array
- 5.returns an empty string for an empty object
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.