1. /**
  2. * Diffs two datasets of query strings and logs differences.
  3. *
  4. * @param {string} str1 The first query string.
  5. * @param {string} str2 The second query string.
  6. * @param {string} [keyPrefix=''] Optional prefix for keys in the diff output.
  7. */
  8. function diffQueryStrings(str1, str2, keyPrefix = '') {
  9. const diffLog = [];
  10. const parseQueryString = (str) => {
  11. const params = {};
  12. if (!str) return params; // Handle empty string
  13. const pairs = str.split('&');
  14. for (const pair of pairs) {
  15. const [key, value] = pair.split('=');
  16. if (key) {
  17. params[key] = value || ''; // Handle missing value
  18. }
  19. }
  20. return params;
  21. };
  22. const params1 = parseQueryString(str1);
  23. const params2 = parseQueryString(str2);
  24. // Find keys present in str1 but not in str2
  25. for (const key in params1) {
  26. if (!(key in params2)) {
  27. diffLog.push(`${keyPrefix}[${key}] Removed from str2`);
  28. }
  29. }
  30. // Find keys present in str2 but not in str1
  31. for (const key in params2) {
  32. if (!(key in params1)) {
  33. diffLog.push(`${keyPrefix}[${key}] Added to str2`);
  34. }
  35. }
  36. // Find keys with different values
  37. for (const key in params1) {
  38. if (params1[key] !== params2[key]) {
  39. diffLog.push(`${keyPrefix}[${key}] Value changed from "${params1[key]}" to "${params2[key]}"`);
  40. }
  41. }
  42. // Find keys present in both strings but with different values
  43. for (const key in params1) {
  44. if (key in params2 && params1[key] !== params2[key]) {
  45. diffLog.push(`${keyPrefix}[${key}] Value changed from "${params1[key]}" to "${params2[key]}"`);
  46. }
  47. }
  48. if (diffLog.length > 0) {
  49. console.log("Query String Differences:");
  50. diffLog.forEach(logEntry => console.log(logEntry));
  51. } else {
  52. console.log("No differences found.");
  53. }
  54. }

Add your comment