Jmeter Javascript Switch Statement Always Matches Default - javascript

I have been looking in both Jmeter and Javascript forums and can't figure out why this case statement is always matching to the default and I wondered if it was a Jmeter condition that I was missing.
I don't think it is a data problem. The URLTYPE_ variable is being set by a CSV input. Here are two lines from it.
Thumbnail,XXXXXX/XXXXXX,
Caption,XXXXXXXX/XXXXXX,
Code Snippet :
var t = vars.get("URLTYPE_");
log.info("starting");
log.info(t);
switch (t)
{
case "Thumbnail":
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("thumb");
break;
case "Caption":
vars.put("CGIURL", "capt");
vars.put("LBURL", "c");
log.info("c");
break;
default:
vars.put("CGIURL", "thumbres");
vars.put("LBURL", "thumb");
log.info("Default");
break;
}
log.info("stopping");

Try using if clauses instead of case with == comparison.

Related

Javascript using a switch statement with `case x` for a wide range of numerical values x

I wish to use case within a switch switch statement like so:
case 'transfer' + amount:
sql.get(`SELECT * FROM scores WHERE userId ="${userID}"`).then(row => {
sql.run(`UPDATE scores SET points = ${row.points - amount} WHERE userId = ${userID}`);
bot.sendMessage({
to:channelID,
message: `You have transferred ` + amount + ` points. You currently have ${row.points} points.`
})
break;
If it sees transfer10 I want the code to take that value 10 to be amount however I have no idea how to do that.
Thanks in advance :)
I do not think you can create switch statement with dynamic-generated case statements. I also do not see any real advantage of doing this, plus the logic behind this it would be hard to understand from anyone else who will be reading the code.
What about using the switch statement do determine the art of action and accessing the _amount_in the case statements ?
var amount, action;
// some code
...
amount = 2;
// some code
...
action = 'transfer' // or delete, update ...
// some code
...
switch(action) {
case 'transfer':
// do some SQL and access the amount
...
break;
case 'delete':
// do some SQL and access the amount
break;
default:
// some default action
}
If you really need something like a dynamically-created switch-statement look at the first answer from this question.

javaScript placeholder in array for pattern match

I have a js array like that:
let data = [{status:"stay",points:[1,2,3,4,5]}, {status:"move",points:[1,2,3,4,5]},{status:"stay",points:[1,2,3,4,5]}]
And I want to do some pattern match, here is my code:
switch (data){
case [{status:"move",_},{status:"stay",_},{status:"move",_}]:
console.log("successfully!")
}
And I don't care the points array, but in js the placeholder "_" not exist, actually I know other method to do this, but if we just use switch-case, can it be solved?
I am a newbie of js, anynoe knows how to do it?
If I understand what you're trying to do correctly, you might try reducing your array to a string, and then use that string in the switch statement. Something like this:
var actionString = ""
data.forEach(function(datum) {
actionString += datum.status + ' ';
});
// Remove extra space at the end
actionString.trim();
console.log(actionString); // "move stay move"
Then your switch statement would be:
switch(actionString) {
case "move stay move":
console.log('success!');
break;
case "stay move stay":
console.log('failure?');
break;
/* etc */
}
Try
switch (data.status){
case "stay":
case "move":
console.log("successfully!")
break;
}
Documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

passing values into functions in javascript

Not sure why the code below is not working. It should take in a string and convert a G to a C and an A to a T and vice versa. However, it collects the input string but doesn't provide any output i.e. the alert just says "here is your reverse complement DNA"
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
It should take in a string and convert a G to a C and an A to a T and vice versa.
Then you don't need the reverse(), because you are pushing in order.
Also, Make sure that you are entering uppercase letters into the prompt.
Else, you can force the uppercase.
This is the code with the two fixes:
function reverseComplement(dnaString) {
var reverseC = [];
var dnaArr = dnaString.toUpperCase().split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.join('');
}
var dnaSequence = prompt("Enter your DNA sequence here", "");
var newSequence = reverseComplement(dnaSequence);
alert("here is your reverse complemented DNA: " + newSequence);
The main lesson you need here is how to test and debug your JavaScript code.
First, get familiar with the JavaScript debugger in your browser. Instead of wondering why your code doesn't work, you can see directly what it is doing. Every modern browser has built-in JavaScript debugging tools; for example here is an introduction to the Chrome DevTools.
Second, when you are testing a function like this, don't use prompt() or alert(). Instead, provide a hard coded input string and use console.log() to display the output in the JavaScript debug console. This way you can run the same test case repeatedly. After you get one test case to work, you can add others.
There are several JavaScript testing frameworks if you want to get fancy, but to start with, simply using a hard coded input and console.log() output plus inspection in the JavaScript debugger is fine.
To make it easy to debug a function when you first write it, add a debugger; statement at the beginning. Then it will stop in the debugger and you can single-step through the code to see which parts of your function actually get executed and what all your variable values are at each step of the way.
For example (since it sounds like you were mistakenly testing with lowercase input), you might do this:
var dnaSequence = 'actg';
var newSequence = reverseComplement(dnaSequence);
console.log(newSequence);
function reverseComplement(dnaString) {
debugger;
var reverseC = [];
var dnaArr = dnaString.split('');
for (var i = 0; i < dnaArr.length; i++) {
switch (dnaArr[i]) {
case 'A':
reverseC.push('T');
break;
case 'T':
reverseC.push('A');
break;
case 'C':
reverseC.push('G');
break;
case 'G':
reverseC.push('C');
break;
}
}
// Reverse and rejoin the the string
return reverseC.reverse().join('');
}
Now, if you have the DevTools open, it will stop in the debugger at the first line of your function. You can single-step through the function to see which of the case statements it actually goes to, and you will see that it doesn't go to any of them. You can also look at the value of dnaArr[i] and see whether it matches any of the case values.

Javascript switch not working with <option> tag values

I have the following HTML:
<select id="rankBox">
<option value="0">100</option>
<option value="1">150</option>
<option value="2">200</option>
<option value="3">250</option>
<option value="4">300</option>
<option value="5">350</option>
<option value="6">400</option>
</select>
<input type="Submit" id="button1" value="Generate" onclick="doStuff()">
and the following Javascript:
function doStuff() {
var choice = $("#rankBox option:selected").val();
console.log(choice);
switch (choice) {
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
In short, I have a switch statement which is supposed to check the value of the option the user has selected. As you may see, I have added console.log to see if the problem is with acquiring the user's input, but that is not the issue. The issue is the switch statement, which just does not work.
Am I using wrong syntax or something?
jsFiddle: http://jsfiddle.net/3qTHW/2/ (jsFiddle doesn't work in my browser at all, says doStuff() is not defined)
Thanks in advance.
It's not an integer, it's a string, as all values from an element are strings.
You'll have to either parse it as an integer :
function doStuff() {
var choice = parseInt( $("#rankBox option:selected").val(), 10);
....etc
or change the switch to work with strings (you should be trimming)
switch ( $.trim(choice) ) {
case '0':
case '1':
....etc
This was an easy problem, by looking at the code one could see that the line var choice = $("#rankBox option:selected").val(); is adding string to variable choice. And that is the reason none of the case statements worked and the default code executed.
The best way not to run into such problems is to "Debug" your JavaScript code properly. This will save you a lot of precious time and you will find the root cause to each problem yourself.
To debug your code, you can use Firebug extension in Firefox. This will actually stop the code execution for you and guide you line by line telling you the state of each variable at every line of code. So in case of your problem, all I did was add your code in .html file and ran it in Firefox with "Debugger" points specified. The JS code looked like this.
function doStuff() {
var choice = $("#rankBox option:selected").val();
debugger; // This is the point where the debugging starts
console.log(choice); // console.log wont help as it did not tell me the type
switch (choice) { // Here Firebug tells me that choice is actually a string
case 0:
case 1:
colorQ = "^7";
break;
case 2:
colorQ = "^L";
break;
case 3:
colorQ = "^A";
break;
case 4:
colorQ = "^8";
break;
case 5:
colorQ = "^+";
break;
case 6:
colorQ = "^<";
break;
default:
alert("Something went wrong");
break;
}
alert(colorQ);
}
Note I put a "debugger" above console.log(). From this point onward, the code stopped at each line and I could see the value in each variable. This helped me notice string value in choice.
Happy Debugging :)
Use javascript parseInt() method like this :
var choice = parseInt($("#rankBox option:selected").val());

Javascript switch issue with window.location-string

i am currently working on a simple ipad webapp testpiece and got stuck in a simple switch statement that doesn´t work somehow;
i want to format elements according to javascripts window.location string. This might be embarassing simple to fix; but i somehow don´t get it:
Or is there something special about the window.location?
$(document).ready(function() {
path_c = window.location;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
THX!
Or is there something special about the window.location?
It's a host object, which sometimes act unpredictable. At least, it is an object which evaluates to the href when casted to a string - yet that does not happen when comparing with the switch-cases. Use
var path_c = window.location.href;
window.location returns a Location object, which contains information about the URL of the document and provides methods for changing that URL. So change it to:
var path_c = window.location.href;
I think you want the href property of the window.location object.
path_c = window.location.href;
Full Script
$(document).ready(function() {
path_c = window.location.href;
switch (path_c){
case "http://192.168.1.37/ryba_testground/":
$('#menu-item-22').addClass('current_page_item');
alert(path_c);
break;
case "http://192.168.1.37/ryba_testground/?page_id=7":
$('#menu-item-21').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=9":
$('#menu-item-20').addClass('current_page_item');
break;
case "http://192.168.1.37/ryba_testground/?page_id=11":
$('#menu-item-19').addClass('current_page_item');
break;
}
});
Example: http://jsfiddle.net/9vjY9/
The code seems ok. Try to alert (window.location.href) or console.log(window.location.href), then you can check exactly what does window.location.href gets for each page you test. This might reveal the problem.
You can use window.location.toString() or window.location.href, you even can avoid using switch, with a object map and regular expression to filter your target in url:
var page_idMap = {
'7': '#menu-item-21',
'9': '#menu-item-20',
'11': '#menu-item-19'
}
var id = window.location.href.match(/page_id[=]([0-9]+)/i);
if (!id || !page_idMap(id[1])) {
$('#menu-item-22').addClass('current_page_item');
} else {
$(page_idMap[id[1]]).addClass('current_page_item');
}

Categories

Resources