Problem: Build URLs including arguments.

Setup

You will need copies of the following files:

Motivation

A URL consists of multiple component parts, starting with the webserver identifier, the virtual directories (or controllers/actions) and finally any HTML pair values we want to send to the server during a HTTP GET. For example:

http:\\www.webserver.com\FindProducts\name=Bag&colour=Red&maxprice=10.99

The server prefix is http:\\www.webserver.com
The service postfix we want is FindProducts
The arguments are name=Bag&colour=Red&maxprice=10.99

We want to build a URL that consist of any combination of server prefix, service postfix(es) and arguments.

http:\\www.webserver.com\ProductCategory\category=DVD
http:\\www.webserver.com\Product\Category\Add\category="Books"
http:\\www.webserver.com\AddProduct ← No arguments required

Usage

We need a Url class that will allow us to build a URL by appending the server prefix, any service postfixes and finally any arguments. An example of how this class might be used is shown below:
var urlBuilder: IUrl;
var url: string;

// Get a URL builder
urlBuilder = Url.Create(); 

// Append the webserver prefix
urlBuilder.Append("http://www.testsite.com");

// Append the service postfixes
urlBuilder.Append("Products");

// Append the HTML pair arguments, values are
// provide in an object literal
urlBuilder.AppendArgs({ name: "car", colour: "red" });

// Read the final URL
url = urlBuilder.Url;

window.alert("Built URL is " + url);
The URL builder is created using the static method Create() which returns an object conforming to the IUrl interface. Notice the arguments to be added to the URL are provided as an object literal so they can be converted to pairs by the the HTMLPairsConvertor. A property Url is provided to read the final URL string.

Details

The Url class should look like this:
interface IUrl
{
    Append(urlPart: string): IUrl;
    AppendArgs(args: Object): IUrl;
    Url: string;
}

class Url
{
    // Attributes
    private _url: string = "";

    // Constructor
    constructor()
    {
        throw new Error("Error: Url is a static class");
    }

    // Properties

    // Methods
    static Create(url?: string): IUrl 
    {
        return {
            Url: url ? url : "",

            Append(urlPart: string): IUrl
            {
                // Your code goes here
                return this;
            },

            AppendArgs(args: Object): IUrl
            {
                // Your code goes here
                return this;
            }
        };
    }
}

Hints

  1. You can convert an object literal to HTML pairs like this:
    var values: Object;
    var pairs: string;
    
    values = { name: "Fred", age: 22 };
    HTMLPairsConvertor.ConvertObjToPairs(values);