Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.5 KiB · at f30ac63

Write two functions that read a parameter from a URL query string such as "?a=1&b=two%20words&a=3".

getParam(query, name) returns the value of the first parameter whose decoded key equals name, or is absent when there is none.

  • A leading ? is optional and is not part of the first key.
  • The query is split on &. Empty segments are ignored.
  • Each segment splits at its first = into key and value. A segment with no = has the value "". A value of "" is present, not absent.
  • Keys and values are decoded by replacing every + with a space and then percent-decoding as UTF-8, the way decodeURIComponent does.
  • Some segments have malformed percent escapes (for example %zz or a truncated UTF-8 sequence like %E0%A4%A). A segment whose key cannot be decoded never matches and is skipped. If the first segment whose key matches has a value that cannot be decoded, fail with { kind: "malformed", param }, where param is name. Malformed segments that do not match name are not an error.

getIntParam(query, name, range) reads the same parameter as an integer, where range is { min, max } (inclusive).

  • Fails with { kind: "malformed", param } exactly when getParam would.
  • Fails with { kind: "missing" } when the parameter is absent.
  • The decoded value must be an optional - followed by one or more ASCII digits and nothing else. Otherwise fail with { kind: "not_integer", raw }, where raw is the decoded value.
  • Fails with { kind: "out_of_range", value } when the number is below min or above max.