Skip to content

Parsing a query string

parsingAll subjects

A small parser. Parsers attract defects at their edges — the empty input, the pair with no value, the value containing the separator you split on — and a suite written against the happy path will not visit any of them.

The module under test

1
export function parseQuery(input) {
2
const out = {};
3
if (typeof input !== "string" || input.length === 0) {
4
return out;
5
}
6
const body = input.charAt(0) === "?" ? input.slice(1) : input;
7
for (const pair of body.split("&")) {
8
if (pair.length === 0) {
9
continue;
10
}
11
const index = pair.indexOf("=");
12
const key = index === -1 ? pair : pair.slice(0, index);
13
const value = index === -1 ? "" : pair.slice(index + 1);
14
if (key.length === 0) {
15
continue;
16
}
17
if (Object.prototype.hasOwnProperty.call(out, key)) {
18
const existing = out[key];
19
out[key] = Array.isArray(existing) ? existing.concat(value) : [existing, value];
20
} else {
21
out[key] = value;
22
}
23
}
24
return out;
25
}
26

Your tests

Mutants

Mutation score
Survived
0
Killed
0 / 0
Line coverage
Tests
0
Assertion width
Cycle
    survivedkilledtimed outequivalentnot run