Query param formatter

Benchmark created on


Setup

const testOperations = {
	width: 200,
	withSlash: "value/with/slash",
	boolean: true,
	// Should include false values
	isFalse: false,
	// Should exclude undefined values
	isUndefined: undefined,
	// Should exclude null values
	isNull: null,
	withAmpersand: "value&with&ampersand",
	withEqual: "value=with=equal",
	withComma: "value,with,comma",
};

Test runner

Ready to run.

Testing in
TestOps/sec
Query formatter
const queryFormatter = (operations) => {
	const params = new URLSearchParams();
	Object.entries(operations).forEach(([key, value]) => {
		if (Array.isArray(value)) {
			value.forEach((v) => params.append(key, v));
		}
		if (value !== undefined && value !== null) {
			params.set(key, String(value));
		}
	});
	return params.toString();
};

const out = queryFormatter(testOperations)

ready
With encoding
const createFormatter = (
	operationJoiner,
	valueJoiner,
) =>
(operations) =>
	Object.entries(operations).map(([key, value]) => {
		if (value === undefined || value === null) {
			return "";
		}
		return `${encodeURIComponent(key)}${valueJoiner}${
			encodeURIComponent(String(value))
		}`;
	}).filter(Boolean).join(operationJoiner);
	

const formatter = createFormatter("&", "=");
const out = formatter(testOperations)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.