Skip to content

Instantly share code, notes, and snippets.

@yoko
Created December 9, 2010 06:15
Show Gist options
  • Save yoko/734398 to your computer and use it in GitHub Desktop.
Save yoko/734398 to your computer and use it in GitHub Desktop.
hashState = function(queries) {
var k, q;
if (queries === null) {
// fx 3.0.x reloads page when hash is empty
location.hash = '#';
return null;
}
else if (!queries) {
q = location.hash.slice(1);
// fx decodes automatically
if (!$.browser.mozilla) {
q = decodeURIComponent(q);
}
return hashState.parse(q);
}
else {
q = hashState.stringify(queries);
location.hash = q;
return q;
}
};
hashState.stringify = function(queries) {
var k, v, ret = [];
for (k in queries) {
v = queries[k];
if (typeof v != 'number' && !v || typeof v == 'function') {
continue;
}
if (v === true) {
ret.push(encodeURIComponent(k));
}
else {
ret.push([encodeURIComponent(k), encodeURIComponent(queries[k])].join('='));
}
}
return ret.join('&');
};
hashState.parse = function(query) {
var queries = query.split('&'),
i = 0, q, m, key, value,
ret = {};
for (; q = queries[i]; ++i) {
m = /^([^=]+)=?(.*)$/.exec(q) || [];
if (m[1]) {
key = decodeURIComponent(m[1]);
value = m[2] && decodeURIComponent(m[2]);
value = value ?
isNaN(Number(value)) ? value : Number(value) :
true;
ret[key] = value;
}
}
return ret;
};
module('hashState');
test('hashState', 5, function() {
var params = { foo: 'bar', 'い': 'ろ'},
ret;
ret = hashState(params);
if ($.browser.mozilla) {
equal(location.hash, '#foo=bar&い=ろ', 'save state to location.hash (Firefox)');
}
else {
equal(location.hash, '#foo=bar&%E3%81%84=%E3%82%8D', 'save state to location.hash');
}
equal(ret, 'foo=bar&%E3%81%84=%E3%82%8D', 'return stringify');
deepEqual(hashState(), params, 'load state from location.hash');
ret = hashState(null);
strictEqual(location.hash, '', 'clear location.hash');
strictEqual(ret, null, 'return null');
});
test('hashState.stringify', 1, function() {
var params = {
'string' : 'a',
'string0' : '0',
'string1' : '1',
'number0' : 0,
'number1' : 1,
'undefined': undefined,
'null' : null,
'true' : true,
'false' : false,
'function' : function() {},
'い' : 'ろ'
};
equal(hashState.stringify(params), 'string=a&string0=0&string1=1&number0=0&number1=1&true&%E3%81%84=%E3%82%8D', 'stringify');
});
test('hashState.parse', 1, function() {
var params = 'string=a&string0=0&string1=1&number0=0&number1=1&true&%E3%81%84=%E3%82%8D';
deepEqual(hashState.parse(params), {
'string' : 'a',
'string0' : 0,
'string1' : 1,
'number0' : 0,
'number1' : 1,
'true' : true,
'い' : 'ろ'
}, 'parse');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment