Skip to content

Instantly share code, notes, and snippets.

@yurkimus
Last active July 14, 2024 02:15
Show Gist options
  • Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Making URLs
function URLPathname(pathname, search, hash) {
this.pathname = pathname;
this.search = new URLSearchParams(search);
this.hash = hash;
}
URLPathname.prototype.resolve = function (parameters) {
if (this.pathname) {
var resolved = this.pathname;
switch (Object.prototype.toString.call(parameters)) {
case '[object Array]':
for (var parameter of parameters)
resolved = resolved.replace(':' + parameter.at(0), parameter.at(1));
break;
case '[object Object]':
for (var parameter in parameters)
resolved = resolved.replace(':' + parameter, parameters[parameter]);
break;
}
if (this.search.size && this.hash) {
return resolved + '?' + this.search + '#' + this.hash;
} else if (this.search.size) {
return resolved + '?' + this.search;
} else if (this.hash) {
return resolved + '#' + this.hash;
} else {
return resolved;
}
}
};
URLPathname.prototype.toString = function () {
if (this.pathname) {
if (this.search.size && this.hash) {
return this.pathname + '?' + this.search + '#' + this.hash;
} else if (this.search.size) {
return this.pathname + '?' + this.search;
} else if (this.hash) {
return this.pathname + '#' + this.hash;
} else {
return this.pathname;
}
}
};
URLPathname.prototype[Symbol.toPrimitive] = function (hint) {
switch (hint) {
case 'string':
case 'default':
return this.toString();
default:
return null;
}
};
URLPathname.of = (...parameters) => new URLPathname(...parameters);
URLPathname[Symbol.toStringTag] = 'URLPathname';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment