Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Last active August 24, 2018 09:36
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save barneycarroll/5310151 to your computer and use it in GitHub Desktop.
Save barneycarroll/5310151 to your computer and use it in GitHub Desktop.
An ultra-small URI parsing function that accepts a URI-like string & returns an object with all the string properties of the native Location object for that string. Works using native property detection, without received wisdom (ie dictionaries, inference, etc).

window.location instanceof Location === true, but invoking Location is illegal. Once you've executed the code below, window.location instanceof Location === false, but you will be able to invoke new Location( /* URI-like string */ ) to return an object with similar properties to the window.location object.

export default x=>document.createElement('a').href=x
var Location = (function LocationClosure(){
var properties = {};
// Create and return a link with the given URI
function makeLink( URI ){
var link = document.createElement( 'a' );
link.href = URI;
return link;
}
// IE<9-compatible hasOwnProperty
function hasOwn( subject, candidate ){
if( subject.hasOwnProperty ){
return subject.hasOwnProperty( candidate );
}
else {
return candidate === 'hasOwnProperty' ? false : Object.prototype.hasOwnProperty.call( subject, candidate );
}
}
// Execute once to establish which static properties are shared by location and any given link element
void function getLocationProperties(){
var location = window.location;
var link = makeLink( '' );
var x;
for( x in location ){
if( hasOwn( location, x ) && typeof location[ x ] === 'string'){
properties[ x ] = true;
}
}
}();
function Location( URI ){
// Force constructor invocation
if( !( this instanceof Location ) ){
return new Location( URI );
}
var location = this;
var link = makeLink( URI );
var x;
for( x in properties ){
location[ x ] = link[ x ];
}
return location;
}
Location.prototype.toString = function toString(){
return this.href;
};
return Location;
}());
function Location(x){return document.createElement('a').href=x}
@barneycarroll
Copy link
Author

Created when I wanted a tiny subset of Rodney Rehm's excellent URI.js plugin, despite my full sympathy with his thoughts on incomplete subsets as an anti-pattern.

@rodneyrehm
Copy link

There is nothing - absolutely nothing - wrong with creating tiny subsets. Not testing them is bad, but you know that already. My primary concern with "lightweight" is that it's being used as a marketing buzzword and all too often translates to »I didn't care about doing it right«. I don't see that with your subset. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment