E. Skwarka
E. Skwarka

Reputation: 5

Condensing similar functions

So what I'm trying to do is convert a series of functions like:

function classAClickSell(){
	if (classASupply>=1) {
		cash = cash + classAValue;
		document.getElementById("cash").innerHTML = cash;
		classASupply = classASupply - 1;
		document.getElementById("classASupply").innerHTML = classASupply;
	};
};

function classBClickSell(){
	if (classBSupply>=1) {
		cash = cash + classBValue;
		document.getElementById("cash").innerHTML = cash;
		classBSupply = classBSupply - 1;
		document.getElementById("classBSupply").innerHTML = classBSupply;
	};
};

and am trying to get them all to resemble something more along the lines of:

function ClickSell(class){
	if (class.concat('Supply') >= 1) {
		cash = cash + class.concat('Value');
		document.getElementById("cash").innerHTML = cash;
		class.concat('Supply')--;
		document.getElementById(class.concat('Supply')).innerHTML = class.concat('Supply');
	}
}

and I was wondering if there is a way to do this, I can't seem to find one. If anyone can help out or point me in the right direction I will be stocked.

Upvotes: 0

Views: 55

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521289

Try this code:

function classClickSell(input, node) {
    if (input >= 1) {
        cash += input;
        document.getElementById("cash").innerHTML = cash;
        --input;
        document.getElementById(node).innerHTML = input;
        return input;
    };
};

classClickSell(10, "classASupply");

If classASupply is actually global, and you need a potential decrement to stick after the function call, then you can just assign it to the return value of the above function, i.e.

var classASupply = 10;
classASupply = classClickSell(10, "classASupply");

Upvotes: 1

Daniel Centore
Daniel Centore

Reputation: 3349

You can do something like this to access the variables, assuming the variables are global in scope:

function classClickSell(cls){
    if (window["class" + cls + "Supply"] >= 1) {
        cash = cash + window["class" + cls + "Value"];
        document.getElementById("cash").innerHTML = cash;
        window["class" + cls + "Supply"] = window["class" + cls + "Supply"] - 1;
        document.getElementById("class" + cls + "Supply").innerHTML = window["class" + cls + "Supply"];
    };
};

See #1441532 for other ways you might access those variables.

And don't use class as a variable/parameter name -- it's reserved.

Upvotes: 1

Related Questions