Okay, so this may be a repeat, but I personally haven't seen anything on the internet or in Stackoverflow about this.
I am working on a game project and I have been trying to make a text-based game.
In this game, I have a switch statement, for when the user enters a command.
So far I have things for Inventory and Look (Look around the environment), but how do I work with specific things in a switch statement?
For example:
submit = function(input) {
switch(input) {
case "LOOK":
lookaround();
break;
case "LOOK AT" + item:
look();
}
}
It is the LOOK AT line I am having issues with. I do not know how I can make a string work in that format, unless I had a case for every single item individually, example case "LOOK AT ORANGE" or case "LOOK AT TREE".
I hope I am explaining this thoroughly enough. Can anyone give me some advice?
Thanks
EDIT
I think it is important to note that the user is typing the input into an input box, so the value of the input is going to be a string.
If it will help to see the code I have made, please let me know in the comments below.
EDIT
THANKS FOR YOU HELP GUYS!
I used a regular expression (Thanks #red-devil) and a mixture of slicing. It works perfectly now!
Switch works with constants, not expressions like 'LOOK AT' + anything.
You could define an object for map any of your cases to your own functions. Like that:
var looks = {
'lookat-something' : function() {
alert('something');
},
'lookat-other-thing' : function() {
alert('other thing');
},
};
var x = 'lookat-other-thing';
looks[x]();
It much more flexible than using switch in any way.
If I understood you right, you want the user to be able to input LOOK AT and then any item name. The problem here is that you have this ominous item variable that could stand for anything and this is not going to work.
I would suggest one of these two ways:
Going along the lines of your example:
submit = function (input) {
switch (true) {
case input == "LOOK":
alert("Look")
break;
case input.startsWith("LOOK AT"):
alert(input)
break;
}
}
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
And secondly, and this is the method I would recommend, you implement a way to parse any input into a command and parameters. A way to do this is to split the input at every space character and then the first value is the command and the rest would be the parameters. This would require you to use a one word command like LookAt and not LOOK AT.
So something like this:
function submit(input) {
var parts = input.split(" ");
var cmd = parts[0];
var args = parts.slice(1);
switch (cmd) {
case "Look":
lookAround();
break;
case "LookAt":
lookAt(args[0]);
break;
}
}
Related
What can be the JavaScript code for translating app from one language to another for about 30 words, based on "switch"?
Well, it is like any other switch statement aswell, just with 30 cases. It should look something like this:
function translateWord(word) {
let result = '';
switch (word.toLowerCase()) {
case 'apfel': result = 'apple'; break;
case 'kette': result = 'chain'; break;
case 'pflanze': result = 'plant'; break;
}
return result;
}
document.getElementById('result').textContent = translateWord('Apfel');
<h1 id="result"></h1>
the function "translateWord" takes a word, in this case 'Apfel' (german word for apple). That word is passed to the switch statement and transformed to lowercase so it is not case sensitive. After the result is returned and put into the <h1>-Tags on the html page.
Now if you just want to translate 30 words, this might be an option, but common dicionaries have well over six digits of words. So you should look to use a database.
Also JSON might be an option aswell. In my opinion the better way.
const germanToEnglisch = {
word1 = 'Wort1',
word2 = 'Wort2',
word3 = 'Wort3'
};
You can now access the word you want to translate with germanToEnglisch[word1] or with germanToEnglisch.word1, both should work. This requires you to have to word implemented in the object above of course. Hope this helps, i am not sure if i understood your question correctly, as for me it is a bit vague :)
In Adobe Brackets, I am getting warnings from JSLint when writing strict code ['use strict'] that my switch case statement is incorrectly formatted:
eg. Expected 'case' at column #, not column #
If I move everything inside the switch statement back back one "tab" JSLint is happy.
But, Adobe Brackets (And Similar Code Applications) wants to indent the case statements, and even when using Code Beautify it also formats the code to have an indent before the case statement.
When using strict code, is what JSLint is suggesting really the proper way of to format the switch-case statements?
Is there a way to fix/make JSLint in Adobe Brackets so it thinks this indentation is correct? (I would like to stick to not hacking up the JSLint Code)
Why would Editors format the switch-case statement this way if strict code does not want you to do that?
Am I really just doing something wrong here?
Is this just a downside of JSLint and is there a way to avoid using the switch-case statement then altogether thus in the process also making JSLint happy?
Should I really just stop using JSLint altogether? And Switch to something else?
This Code is nested in a for loop:
switch (curButton.button.innerText.toLowerCase()) {
case this.Part1.Button.ButtonText.toLowerCase():
this.Part1.Button.ButtonText = curButton.button.innerText;
this.Part1.Button.Element = curButton.button;
this.Part1.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part1.Button);
break;
case this.Part2.Button.ButtonText.toLowerCase():
this.Part2.Button.ButtonText = curButton.button.innerText;
this.Part2.Button.Element = curButton.button;
this.Part2.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part2.Button);
break;
case this.Part3.Button.ButtonText.toLowerCase():
this.Part3.Button.ButtonText = curButton.button.innerText;
this.Part3.Button.Element = curButton.button;
this.Part2.Button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts.Part3.Button);
break;
}
Here is some basic code that will reproduce this on https://www.jslint.com/
function abcd() {
var a;
var b;
switch (a) {
case 1:
a=b;
break;
case 2:
b=a;
break;
}
}
This sounds like a problem with JSLint.
It's not exactly what you were asking, but one way to re-formulate the code and avoid switch entirely (and thus the problems JSLint has with switch) is to .find the Part whose ButtonText matches. Then use bracket notation to look up the button on the this:
const currentText = curButton.button.innerText.toLowerCase();
const matchingPart = ['Part1', 'Part2', 'Part3']
.find(part => currentText === this[part].Button.ButtonText.toLowerCase());
if (matchingPart) {
const { button } = this[matchingPart];
button.ButtonText = curButton.button.innerText;
button.Element = curButton.button;
button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts[matchingPart].Button);
}
If you can control the shape of the this object, it would probably be easier if the Parts were an array, instead of 3 different properties. Then, you could .find over that array, instead of hard-coding the 3 Part properties.
I'd consider the code above to be perfectly fine, but to make it pass all of JSLint's (IMO - opinionated and not-so-good) rules, it'd have to be
const currentText = curButton.button.innerText.toLowerCase();
const props = ["Part1", "Part2", "Part3"];
const matchingPart = props.find(function(part) {
return currentText === this[part].Button.ButtonText.toLowerCase();
});
if (matchingPart) {
const { button } = this[matchingPart];
button.ButtonText = curButton.button.innerText;
button.Element = curButton.button;
button.CurrentClass = curButton.button.className;
console.log(smgData.PodCast.Parts[matchingPart].Button);
}
First time writing Javascript. I just would like know if there is a shorter way of writing this:
<p id="demo"></p>
<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;
if (letter === "5544") {
text = "Abar, Marlon 1,800";
} else if (letter === "5545") {
text = "Pia, Darla 1,800";
} else if (letter === "5546") {
text = "Salazar, Alex 1,500";
//etc...
} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Tried map but I couldn't get it to work.
There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking). However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;
switch (letter) {
case "5544":
text = "Abar, Marlon 1,800";
break;
case "5545":
text = "Pia, Darla 1,800";
break;
// more cases
default:
text = "Incorrect Account Number";
break;
}
This reads a little better than an if else statement in some cases. The default keyword here acts as your else clause in an if else statement. The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544"). If none matches, it hits the default case. The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
'5544': 'Abar, Marlon 1,800'
};
if (letter in obj) {
// do something if found
}
else {
// do something if not found
}
This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values. You can use a switch statement to make it cleaner. Use the object lookup method if you have many values you would like to check.
JavaScript has object (map) literals. Use them for terse code. In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
"5544" : "Abar, Marlon 1,800",
"5445" : "Pia, Darla 1,800",
...
}[ document.getElementById( "myInput" ).value ];
you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.
I have a Javascript-based bot for a Xat chatroom which also acts as an AI. I've recently decided to redo the AI part of it due to it becoming an absolutely massive chain of else if statements, becoming nearly impossible to work with.
I did some research and came up with a new idea of how to handle responses. I'll give you the code segment first:
function msgSwitch(id,msgRes) {
var botResponse = [];
switch (msgRes) {
case (msgRes.indexOf("hi") !=-1):
botResponse.push("HELLO. ");
case (msgRes.indexOf("how are you") !=-1):
botResponse.push("I AM FINE. ")
case (msgRes.indexOf("do you like pie") !=-1):
botResponse.push("I CAN'T EAT. THANKS, ASSHAT. ")
default:
respond (botResponse);
spamCount(id);
break;
}
}
The idea here is to check msgRes (the user's input) and see how many cases it matches. Then for each match, it'll push the response into the botResponse array, then at the end, it'll reply with all the messages in that array.
Example
User Msg: Hi! How are you?
msgRes: hi how are you
Bot Matches:
hi > pushes HELLO. to array
how are you > pushes I AM FINE. to array
Bot Responds: HELLO. I AM FINE.
This in turn saves me the trouble of having to write an if for each possible combination.
However, after looking into it some more, I'm not sure if it's possible use indexOf inside of a switch. Does anyone know of a way around this or have a better idea for handling responses in the same manner?
EDIT:
To Avoid the XY Problem (To clarify my problem)
I need a clean alternative to using a massive chain of else if statements. There are going to be hundreds of word segments that the bot will respond to. Without the ability for it to keep searching for matches, I'd have to write a new else if for every combination.
I'm hoping for a way to have it scan through every statement for a match, then combine the response for each match together into a single string.
EDIT 2:
I should also add that this is being ran on Tampermonkey and not a website.
you just need to compare to true instead of msgRes (since cases use === comparison), and use break to prevent the annoying fall-though of the switch behavior:
function msgSwitch(id,msgRes) {
var botResponse = [];
switch (true) {
case (msgRes.indexOf("hi") !=-1):
botResponse.push("HELLO. "); break;
case (msgRes.indexOf("how are you") !=-1):
botResponse.push("I AM FINE. "); break;
case (msgRes.indexOf("do you like pie") !=-1):
botResponse.push("I CAN'T EAT. THANKS, ASSHAT. "); break;
default:
respond (botResponse);
spamCount(id);
break;
}
}
This is a perfectly valid logical forking pattern, known as an "overloaded switch". A lot of folks might not realize that each case: is an expression, not just a value, so you could even put an IIFE in there if needed...
My two cents for the gist of what you're trying to do:
function msgSwitch(id, msgRes) {
var seed = {'hi': 'HELLO. ', 'how are you': 'I AM FINE'};
var botResponse = [];
for (var key in seed) {
if (msgRes.indexOf(key) !== -1) {
botResponse.push(seed[key]);
}
}
}
In my opinion it is easier to change this program as you only have to edit the seed if you have more responses in the future. You can even stash the seed on some json file and read it (via ajax) so the program does not need to be changed if there are additional messages.
I'm not guru of javascript, so don't blame me much.
My task is to find and replace text inside html page, so every number should be replaced with it's value multiplied by some amount.
e.g. 123 -> 104.55(123*0.85), 245 -> 208,25(245*0.85) etc.
Currently my code is like following:
$('body').html(
$('body').html().replace(/([0-9\.]+)/g, eval("$1*0.85"))
);
eval("$1*0.85") return NaN while trying parseFloat($1)*0.85 also does not return correct results
Can someone advise?
Thanks.
You probably don't want to take the whole page's HTML and replace it with updated HTML, because all of the elements get torn down and recreated, which has implications for event handlers and the like.
It happens that just yesterday I answered this other question here. The answer can be applied quite easily to your situation.
Update: Since you're not moving the result into a new element, the code actually gets simpler:
walk(document.body);
function walk(node) {
var child;
switch (node.nodeType) {
case 1: // Element
for (child = node.firstChild;
child;
child = child.nextSibling) {
walk(child);
}
break;
case 3: // Text node
node.nodeValue = node.nodeValue.replace(
/[0-9]+(?:\.[0-9]+){0,1}/g,
function($0) {
msgs.push($0);
var num = parseFloat($0, 10);
if (isNaN(num)) {
return $0;
}
return num * 0.85;
}
);
break;
}
}
Live example
Note that I've modified the regexp a bit, you might want to massage it until it's how you want it. But I wanted to match decimal points only when followed by digits. (It's worth noting that not all cultures use . as the decimal point, but you seemed to in your example, so...)
it should be sth like this,
var x = $('body').html();
x = x.replace(/([0-9.]+)/g, function ( x ){ return x*0.85;});
$('body').html(x);
if you do not consider events, etc