Last active
July 14, 2024 02:15
-
-
Save yurkimus/f1effaa84b8dd9885ebb9493d56f6482 to your computer and use it in GitHub Desktop.
Making URLs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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