Sort keys in createSearch + add tests
This commit is contained in:
15
server/utils/__tests__/createSearch-test.js
Normal file
15
server/utils/__tests__/createSearch-test.js
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
const createSearch = require("../createSearch");
|
||||||
|
|
||||||
|
describe("createSearch", () => {
|
||||||
|
it("omits the trailing = for empty string values", () => {
|
||||||
|
expect(createSearch({ a: "a", b: "" })).toEqual("?a=a&b");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sorts keys", () => {
|
||||||
|
expect(createSearch({ b: "b", a: "a", c: "c" })).toEqual("?a=a&b=b&c=c");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns an empty string when there are no params", () => {
|
||||||
|
expect(createSearch({})).toEqual("");
|
||||||
|
});
|
||||||
|
});
|
@ -1,17 +1,16 @@
|
|||||||
function createSearch(query) {
|
function createSearch(query) {
|
||||||
const params = [];
|
const keys = Object.keys(query).sort();
|
||||||
|
const params = keys.reduce(
|
||||||
|
(memo, key) =>
|
||||||
|
memo.concat(
|
||||||
|
query[key] === ""
|
||||||
|
? key // Omit the trailing "=" from key=
|
||||||
|
: `${key}=${encodeURIComponent(query[key])}`
|
||||||
|
),
|
||||||
|
[]
|
||||||
|
);
|
||||||
|
|
||||||
Object.keys(query).forEach(param => {
|
return params.length ? `?${params.join("&")}` : "";
|
||||||
if (query[param] === "") {
|
|
||||||
params.push(param); // Omit the trailing "=" from param=
|
|
||||||
} else {
|
|
||||||
params.push(`${param}=${encodeURIComponent(query[param])}`);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const search = params.join("&");
|
|
||||||
|
|
||||||
return search ? `?${search}` : "";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = createSearch;
|
module.exports = createSearch;
|
||||||
|
Reference in New Issue
Block a user