Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions lib/stringify.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,14 @@ function stringify(input) {
const value = input[key];
const encodedKey = encodeString(key) + "=";

if (i) {
result += separator;
}

if (Array.isArray(value)) {
valueLength = value.length;
if (valueLength === 0) {
continue;
}
if (result.length > 0) {
result += separator;
}
for (let j = 0; j < valueLength; j++) {
if (j) {
result += separator;
Expand All @@ -56,6 +58,9 @@ function stringify(input) {
result += getAsPrimitive(value[j]);
}
} else {
if (result.length > 0) {
result += separator;
}
result += encodedKey;
result += getAsPrimitive(value);
}
Expand Down
7 changes: 7 additions & 0 deletions test/stringify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ test("should coerce numbers to string", () => {
assert.strictEqual(qs.stringify({ foo: Number.POSITIVE_INFINITY }), "foo=");
});

test("should skip empty array values without leaving stray separators", () => {
assert.strictEqual(qs.stringify({ a: [], b: "1" }), "b=1");
assert.strictEqual(qs.stringify({ a: "1", b: [] }), "a=1");
assert.strictEqual(qs.stringify({ a: "1", b: [], c: "2" }), "a=1&c=2");
assert.strictEqual(qs.stringify({ a: [] }), "");
});

test("should return empty string on certain inputs", () => {
assert.strictEqual(qs.stringify(undefined as never), "");
assert.strictEqual(qs.stringify(0 as never), "");
Expand Down
Loading