Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Last active April 15, 2017 20:52
Show Gist options
  • Save aeinbu/c78996dd5a51ac4fbd2f to your computer and use it in GitHub Desktop.
Save aeinbu/c78996dd5a51ac4fbd2f to your computer and use it in GitHub Desktop.
define([], function () {
"use strict";
function parse(querystring) {
var obj = {};
if (querystring) {
var params = querystring.split(/&|\?/);
for (var i = 0; i < params.length; i++) {
var param = params[i];
var paramParts = param.split('=');
if (paramParts.length == 2) {
var name = paramParts[0];
var value = paramParts[1];
obj[name] = value;
}
}
}
return obj;
}
function format(obj) {
var count = 0;
var querystring = '';
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (count++) {
querystring += '&';
}
querystring += key + '=' + obj[key].toString();
}
}
return querystring;
}
return {
parse: parse,
format: format
};
});
@aeinbu
Copy link
Author

aeinbu commented Aug 14, 2015

module("querystring");

QUnit.test("Parse should return an object containing all querystring values", function (assert) {
    var input = "?lat=123&lon=456";
    var expected = { lat: "123", lon: "456" };

    var done = assert.async();

    require(["utils/querystring"], function (querystring) {
        var res = querystring.parse(input);

        propEqual(res, expected);

        done();
    });
});

QUnit.test("Parse should return an empty object if querystring is an empty string", function (assert) {
    var input = "";
    var expected = {};

    var done = assert.async();

    require(["utils/querystring"], function (querystring) {
        var res = querystring.parse(input);

        propEqual(res, expected);

        done();
    });
});

QUnit.test("Parse should return an empty object if querystring is null", function (assert) {
    var input = null;
    var expected = {};

    var done = assert.async();

    require(["utils/querystring"], function (querystring) {
        var res = querystring.parse(input);

        propEqual(res, expected);

        done();
    });
});

QUnit.test("Create a querystring of all properies of an object", function (assert) {
    var input = { lat: 123, lon: 456 };
    var expected = 'lat=123&lon=456';

    var done = assert.async();

    require(["utils/querystring"], function (querystring) {
        var res = querystring.format(input);

        equal(res, expected);

        done();
    });
});

QUnit.test("Create a querystring should exclude properties of prototype", function (assert) {
    var proto = { p1: 123 }
    var input = Object.create(proto);
    input.lat = 456;
    var expected = 'lat=456';

    var done = assert.async();

    require(["utils/querystring"], function (querystring) {
        var res = querystring.format(input);

        equal(res, expected);

        done();
    });
});

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