-1

I need to modify some script that runs in a program I use.

The script ONLY plots horizontal lines at specific prices on a chart that has an X & Y axis. Whenever I switch to a new chart, the script will run through all the statements until it gets to the Symbol/name that matches the chart, then it will load the lines.

I am using the never ending "if else statement" to make things as simple as possible for me. I have 650 if else statements, each contains hundreds of "addlines".

There is no relation between Symbol Names, except the letters in the alphabet. All prices/numbers that the symbols contain are random.

But I am looking for a better solution to make it run faster and more efficient instead of having 650 else if statements. I know the commands I used aren't the same I am just generalizing. I hope someone can help.

Multiply the Else if statements by 650 and that's how many there are.

var Symbol
if (Symbol == "AAB") {
    addline(37.5);
    addline(40.9);
    addline(15.5);
    addline(100.5);
    etc....
} else if (Symbol == "ZOB") {
    addline(15.8);
    addline(20.9);
    addline(100.5);
    addline(200.5);
    etc....
} else if (Symbol == "STX") {
    addline(10.9);
    addline(19.8);
    addline(5.5);
    addline(20.2);
    etc....
} else if (Symbol == "AXI") {
    addline(200);
    addline(20);
    addline(5.9);
    addline(9.9);
    etc....
} else if (Symbol == "AXI") {
    ETC.....
}

return;

}
ntalbs
  • 28,700
  • 8
  • 66
  • 83
Trosky6708
  • 83
  • 3
  • 10

3 Answers3

5

You can use map:

var SymbolMap = {
  AAB: [37.5, 40.9, 15.5, 100.5],
  ZOB: [15.8, 20.9, 100.5, 200.5],
  STX: [10.9, 19.8, 5.5, 20.2],
  AXI: [200, 20, 5.9, 9.9],
  // ...
};

var symbol = 'AAB';
SymbolMap[symbol].forEach(function(x) {
  addline(x);
});
ntalbs
  • 28,700
  • 8
  • 66
  • 83
1

You could change it like this which will likely perform better and be alot easier to manage.

var Symbol = 'AAB';
var Symbols = {};

Symbols.AAB = [37.5, 40.9, 15.5, 100.5];
Symbols.ZOB = [15.8, 20.9, 100.5, 200.5];
Symbols.STX = [10.9, 19.8, 5.5, 20.2];
Symbols.AXI = [200, 20, 5.9, 9.9];

for(var x = 0; x < Symbols[Symbol].length; x++) {
    addline(Symbols[Symbol][x]);
}
Jonathan
  • 2,778
  • 13
  • 23
1

Whether or not you consciously intended it, using the Java tag was a good idea, because I think the best option for you would be to create a REST service which accepts a symbol name and returns a JSON structure of values with which your JS code can call addline().

So you might make a call \YourWebApp\GetLines?Symbol=AAB, and the JSON response might look like:

{
    "lines": ["37.5", "40.9", "15.5", "100.5", ...]
}

You can then iterate over the lines array and make the appropriate calls to addline().

It is probably not good practice to store state for hundreds of if-else statements in your JS code. And I think it would be better to keep this business logic on the server side if at all possible.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360