Construtor de URL de JavaScript personalizado

function UrlBuilder(prefix) {
  let cache = null;
  const parameters = {};
  this.getParameter = function(name, defaultValue) {
    return parameters[name] ?? defaultValue;
  };
this.setParameter = function(name, value) {
      const parameter = parameters[name];
      if (parameter === value) {
          return;
      }
      cache = null;
      if (value == null) {
          delete parameters[name];
      } else {
          parameters[name] = String(value);
      }
  };
  this.toString = function() {
    if (cache === null) {
        let url = '';
          const entries = Object.entries(parameters);
          for (const entry of entries) {
              const name = encodeURIComponent(entry[0]);
              const value = encodeURIComponent(entry[1]);
              url += (url ? '&' : '?') + name + '=' + value;
          }
          cache = prefix + url; 
      }
      return cache;
  };
}

// Usage example:

const builder = new UrlBuilder('https://softhunt.net/page');

builder.setParameter('preview', true);
builder.setParameter('admin', 'ranjeet');
builder.setParameter('age', 22);

console.log(builder.toString()); 

builder.setParameter('preview', null);
builder.setParameter('admin', null);

console.log(builder.toString());
Outrageous Ostrich