/**
* Diffs two datasets of query strings and logs differences.
*
* @param {string} str1 The first query string.
* @param {string} str2 The second query string.
* @param {string} [keyPrefix=''] Optional prefix for keys in the diff output.
*/
function diffQueryStrings(str1, str2, keyPrefix = '') {
const diffLog = [];
const parseQueryString = (str) => {
const params = {};
if (!str) return params; // Handle empty string
const pairs = str.split('&');
for (const pair of pairs) {
const [key, value] = pair.split('=');
if (key) {
params[key] = value || ''; // Handle missing value
}
}
return params;
};
const params1 = parseQueryString(str1);
const params2 = parseQueryString(str2);
// Find keys present in str1 but not in str2
for (const key in params1) {
if (!(key in params2)) {
diffLog.push(`${keyPrefix}[${key}] Removed from str2`);
}
}
// Find keys present in str2 but not in str1
for (const key in params2) {
if (!(key in params1)) {
diffLog.push(`${keyPrefix}[${key}] Added to str2`);
}
}
// Find keys with different values
for (const key in params1) {
if (params1[key] !== params2[key]) {
diffLog.push(`${keyPrefix}[${key}] Value changed from "${params1[key]}" to "${params2[key]}"`);
}
}
// Find keys present in both strings but with different values
for (const key in params1) {
if (key in params2 && params1[key] !== params2[key]) {
diffLog.push(`${keyPrefix}[${key}] Value changed from "${params1[key]}" to "${params2[key]}"`);
}
}
if (diffLog.length > 0) {
console.log("Query String Differences:");
diffLog.forEach(logEntry => console.log(logEntry));
} else {
console.log("No differences found.");
}
}
Add your comment