Skip to content

Instantly share code, notes, and snippets.

@avesus
Forked from barneycarroll/Location.es6.min.js
Last active September 10, 2015 13:35
Show Gist options
  • Save avesus/52aacdd63a06a69b3f4c to your computer and use it in GitHub Desktop.
Save avesus/52aacdd63a06a69b3f4c 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.

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;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment