1
\$\begingroup\$

Here is my JavaScript function to manipulate the hash:

var hash = {
 get: function(key){
 var lh = location.hash;
 if(lh.charAt(0) === "#"){
 lh = lh.slice(1);
 }
 var pairs = lh.split("&");
 var obj = [];
 for(var i = 0; i < pairs.length; i++){
 var pair = pairs[i];
 if(pair.indexOf("=") > 0){
 pair = pair.split("=");
 obj[pair[0]] = pair[1];
 }else{
 obj[pair] = 1;
 }
 }
 return typeof key !== 'undefined' ? obj[key] : obj;
 },
 set: function(key, value, cb){
 var newHash = this.removeKey(key);
 if(newHash.length > 1){
 newHash += "&";
 }
 newHash += key + (typeof value != 'undefined' ? "="+value : "");
 var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");
 history.pushState(undefined, document.title, url);
 if(cb){
 cb();
 }
 },
 del: function(key){
 var newHash = this.removeKey(key);
 var url = location.href.split("#")[0] + (newHash !== "#" ? newHash : "");
 history.pushState(undefined, document.title, url);
 },
 removeKey: function(key){
 var string = location.hash;
 if(string.charAt(0) !== "#"){
 string = "#" + string;
 }
 var regex = new RegExp("[#&]"+key+"(=[^&]+|)", 'gi');
 string = string.replace(regex, "");
 if(string.charAt(0) === "&"){
 string = "#" + string.slice(1);
 }
 return string !== '' ? string : '#';
 }
};

I am trying to make it as light as possible.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Feb 27, 2015 at 21:51
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

Streamlined code for get:

get: function(key){
 var lh = location.hash.replace(/^#/, "");
 var pairs = lh.split("&");
 var obj = [], pair;
 for(var i = 0; i < pairs.length; i++){
 pair = pairs[i].split("=");
 if (pair.length === 1) {
 pair.push(1);
 }
 obj[pair[0]] = pair[1];
 }
 return typeof key !== 'undefined' ? obj[key] : obj;
}, 

I also don't see why there's a callback passed to .set()? There's no async operation and the callback is executed at the end of the function with no args so the caller could just put that same code right after the .set() call. There doesn't seem to be any reason for a callback argument.

answered Feb 27, 2015 at 22:07
\$\endgroup\$
1
  • \$\begingroup\$ That really is a lot better. Thanks a lot. P.S. I took out the callback. I just had that there to test something. \$\endgroup\$ Commented Feb 28, 2015 at 3:35

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.