3

Is there a way to make this function not create a global variable while the body is still just an expression on one line (after return).

Seems like if it works with making a global, should be a way to do it with a local

getHashKeyValues = function(h){
    return p={},h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v}),p
}

console.log(getHashKeyValues("#/app/path|key1=value1;key2=value2"))

0

3 Answers 3

4

You can declare p as a function parameter:

getHashKeyValues = function(h,p){
    return p={},h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v}),p
};

That will make p a local variable in the function just like if you declared it with var. It is perfectly valid to call that function with only one argument, p will just be undefined until it gets assigned a value.

Sign up to request clarification or add additional context in comments.

Comments

4

Declare p as a var in the function.

getHashKeyValues = function(h) {
    var p = {};
    h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v){p[k]=v});
    return p;
}

And make it readable–this is an awful way to write this.

Edit Oh, I missed the "one line" requirement, which disqualifies my answer.

Even though I'm right :p

1 Comment

@baao It's actually kind of impressive :)
2

I agree with Dave Newton, but if you really want to do this, add p as an second parameter, then modify it.

getHashKeyValues = function(h, p){
    return p={},h.replace(/[\|;]+([^=;]+)=([^;]*)/gi,function(s,k,v)    {p[k]=v}),p
}

console.log(getHashKeyValues("#/app/path|key1=value1;key2=value2"))

Comments

Your Answer

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.