Game terms dictionary - javascript

I'm pretty new to javascript, but I'm working on a text-based rpg game. I'm trying to figure out how to make it so that if the user types in 'go' or 'walk' or 'run' or 'march' or anything like that, it will run the same command... rather than just doing a bunch of checks using 'or's', I'd prefer to have a dictionary of terms in a separate file that I can check and return a term. How would I go about doing this? Can I use a regular array? if so how do I search it in javascript?
I'd like to get something like
dictionary:
["go"]:["go"];
["walk"]:["go"];
["run"]:["go"];
["march"]:["go"];
I also realize I could be going about this the completely wrong way, so if you have any tips whatsoever they would be very welcome.

One way would be something like this:
var mydict = [
{
words: ['go','walk','run','sprint','move'],
task: 'move'
},
{
words: ['eat','consume'],
task: 'eat'
}
];
Then just iterate over it and check if your input command is in any of the objects' words array.

You could use an object in a separate JS file.
What is a JavaScript object? A JavaScript object is a collection of key/value pairs. I strongly suggest you learn about JavaScript objects, because in JavaScript almost everything is an object.
A simple object looks like this:
var myCommads = {
"go":"go",
"walk":"go",
"run":"go",
"march":"go"
}
An object is key-value based. You can access the values via their matching keys.
myObject['walk']
Will give you the string "go".
Let's say the user inputs a command:
var command = prompt("Please give your command", "");
Now you check if the command is in your object:
if(typeof myCommands[command] == "undefined"){
alert("Invalid command");
}
else{
var realCommand = myCommands[command];
//now do what you want with the command, saved in the variable "realCommand"
}
I realize I might be too much information for someone with little JavaScript experience, but to explain all this in detail I would need a lot more time and would need to write a much longer answer.
The best way to completely understand my answer would be to read up on some tutorials:
the prompt function: JS prompt
the Alert function: JS Alert
JavaScript objects: JS Objects

Related

Javascript program to check if a prompt character is in Multidimensional array

I have a multidimensional array, where I'd like to check if a value is in it.
I tried the code below but it didn't work as intended
How do i check if username is in my multidimensional array?
let matrix = [
['Lol'],
['MyName'],
['Matrix']
];
let username = prompt('Enter Username')
if (matrix.includes(username)) {
alert('YESSS')
} else {
alert('no')
}
console.log(username)
There are a variety of JavaScript idioms to perform this task.
One option is to flatten the array before running include such as the example Hassam Imam posted.
matrix.flat().includes(username)
Issues will arise however depending on how much data is stored in the multidimensional array.
Another option would be to what Konrad Linkowski suggested and leverage some.
matrix.some(array => array.includes(username))
This has a performance increase as it will stop after finding the first case that matches the provided criteria, but the result is boolean. If you just want to know if the value exists I would recommend this solution.
If you wish to know where in the matrix an element is you will want to use find instead of some as it will provide you the index in which it was found.
matrix.find(arr => array.includes(username));
Though this could get quite complex depending on how many dimensions the array has.
Let me know if you have any questions or would like to stub out what this solution may look like.

JS Slack Notification Filter

Utilizing Slack webhooks and webtask.io I've created a notification filter (based off of a generic script I found online) for Slack that, at this time, filters out messages that contain the string NON-SLA. I'm totally new to JS so getting to this point has all been trial and error. I would like to adjust the script to filter out messages that contain one of any number of strings, but I'm at a roadblock mostly because I'm not familiar with the language and have had 0 luck trying out the various solutions that I've found online.
Here's the current filter for just a single string:
function shouldNotify(data) {
return !data.text.includes('NON-SLA');
}
This returns TRUE for shouldNotify and the rest of the script pushes the message to the specified channel.
I couldn't find a way to do something similar to this:
return !data.text.includes('one','two','three');
Looked into using an array, but nothing of what I found seemed like it would work with the existing script as a whole and I just simply do not have the time to attempt to rewrite it. Seems that this would be the most efficient and proper way to do it though.
Full script can be seen here.
Any help at all would be greatly appreciated as, again, I'm out of ideas with my limited knowledge of this.
TIA
You can use Array.some():
function shouldNotify(data) {
const string = ["one", "two", "three"];
return !string.some(string => data.text.includes(string));
}
// Example:
console.log(shouldNotify({text: "four apples"})); // true
console.log(shouldNotify({text: "two oranges"})); // false
Instead of supplying an arrow function to Array.some, you could alternatively make use of Function.bind and write:
return !string.some(String.includes.bind(string));

A good way to implement a string tokenizer ( or use one that's already established )

Found myself in a situation where I was making one of two rookie mistakes:
Writing code that I should get out of a library
Writing super complex code that could be greatly simplified using better patterning
What I'm trying to do is pretty simple, I need to send instructions to some JavaScript code that prints fields from an object to the page. Things started out fine, the following string:
message, tags, date
Easily instructed the code to get these elements from the object using
field_array = instruction_string.split(',')
obj['message'], obj['tags'], obj['date']
Then I realized that I wanted to modify that date field to reflect the time zone I was in. Enabling the string to carry special instructions for a field added a little complexity with regex, but still wasn't too complicated:
message, tags, date(GMT-5)
Using the code:
var special_instruction = /\(.*\)/ig.exec('date(GMT-5)')[2]
RESULT: special_instruction = 'GMT-5'
I realized that I was getting in over my head when I realized that I also wanted to tell the output to adjust the date so that it reflects the time delta since right now instead of printing the actual date:
message, tags, date(GMT-5_)(SINCE_NOW)
The regex that I wrote didn't work:
var special_instruction = /\((.*)\)/ig.exec('last_updated(GMT-5)(since_now)')
RESULT: special_instruction = 'GMT-5)(since_now'
Although there is probably a way to fix the regex, this indicates that I should be using a tool or established pattern to do this instead of writing custom code off the cusp and screwing around with it for way too long.
Are you sure you want to use strings and regular expressions for this?
An alternative would be to use an array and objects for defining the fields that should be printed.
Something like this:
var fields = [{
name: 'message'
}, {
name: 'tags'
}, {
name: 'date',
timezone: 'GMT-5',
since: new Date() // now
}];
For getting the values from that sure be printed you can iterate over the array and look for the name field. If you found an object with name date you can look for additional properties. You could also add new properties very easily.

JSON Weirdness Needs More Elegant Approach

Basically, I'm working on a page that includes four different JSON "thingies" (objetcs,arrays). Forgive my lack of proper terminology.
When I get the JSON, it comes in as an object with a bunch of sub-objects, and each "sub-object" looks like this:
"token":"government",
"title":"Government",
"isSelected":false,
"type":"CATEGORY",
"subtype":"INDUSTRY",
"count":12
So the first task is to loop through each JSON and populate a box full of checkboxes, using the title as the label and the isSelected to indicate the checked status. So far, so good.
BTW, somewhere aslong the way, I picked up a JS script that checks whether an object is JSON or an array, and according to that "quick & dirty" test, my object is an array. Or an array object (you know, the one is created with [ ] and the other with { })?
Anyway, when the end user checks and un-checks checkboxes, I need to keep track of it all and immediately send back changes to the server (when the user clicks a DONE button). The crazy thing is that by looping through the objects, I was able to change the isSelected value to true . . . just not back to false.
for(var i = 0; i < $array.length; i++){
$array[z].isSelected = true;
}
Perhaps I was up too late when I worked on all of this, but using the same approach, I could not change $array[z].isSelected to false when the checkbox got de-selected.
In the end, I converted the JSON "thingy" to a string, search and replaced the corresponding values, and then converted the string back into an object. This is all working now, but I feel as though I've just used up a roll of duct tape on something that could have been put together by snapping the pieces together nicely.
Question: Did I miss the boat totally and is there a simple way to change values of JSON objects?
If so, could you point me in the right direction?
That JSON thingy is just a string representation of a javascript object.
One way of creating an object is
var myObject = {
"myName": "AName",
"myType": "AType"
};
This object can be referenced as myObject, with the properties myObject.myName and myObject.myType containing values AName and AType.
You should be able to just reference the object by name as objName.token objName.title etc.
If you have trouble try parsing the json with javascript then reference the result as above. This should make it easier for you to access, manipulate or delete data in the objects properties as well.
The nesting of these as below can be referenced as myObject.moreProperties.prop1 etc
var myObject = {
"myName": "AName",
"myType": "AType",
"moreProperties": {
"prop1": "vaue1",
"prop2": "vaue2",
}
};

javascript: array of object for simple localization

I need to implement a simple way to handle localization about weekdays' names, and I came up with the following structure:
var weekdaysLegend=new Array(
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
);
I know I could implement something like an associative array (given the fact that I know that javascript does not provide associative arrays but objects with similar structure), but i need to iterate through the array using numeric indexes instead of labels.
So, I would like to handle this in a for cycle with particular values (like j-1 or indexes like that).
Is my structure correct? Provided a variable "lang" as one of the value between "it-it" or "en-us", I tried to print weekdaysLegend[j-1][lang] (or weekdaysLegend[j-1].lang, I think I tried everything!) but the results is [object Object]. Obviously I'm missing something..
Any idea?
The structure looks fine. You should be able to access values by:
weekdaysLegend[0]["en-us"]; // returns Monday
Of course this will also work for values in variables such as:
weekdaysLegend[i][lang];
for (var i = 0; i < weekdaysLegend.length; i++) {
alert(weekdaysLegend[i]["en-us"]);
}
This will alert the days of the week.
Sounds like you're doing everything correctly and the structure works for me as well.
Just a small note (I see the answer is already marked) as I am currently designing on a large application where I want to put locals into a javascript array.
Assumption: 1000 words x4 languages generates 'xx-xx' + the word itself...
Thats 1000 rows pr. language + the same 7 chars used for language alone = wasted bandwitdh...
the client/browser will have to PARSE THEM ALL before it can do any lookup in the arrays at all.
here is my approach:
Why not generate the javascript for one language at a time, if the user selects another language, just respond(send) the right javascript to the browser to include?
Either store a separate javascript with large array for each language OR use the language as parametre to the server-side script aka:
If the language file changes a lot or you need to minimize it per user/module, then its quite archivable with this approach as you can just add an extra parametre for "which part/module" to generate or a timestamp so the cache of the javascript file will work until changes occures.
if the dynamic approach is too performance heavy for the webserver, then publish/generate the files everytime there is a change/added a new locale - all you'll need is the "language linker" check in the top of the page, to check which language file to server the browser.
Conclusion
This approach will remove the overhead of a LOT of repeating "language" ID's if the locales list grows large.
You have to access an index from the array, and then a value by specifying a key from the object.
This works just fine for me: http://jsfiddle.net/98Sda/.
var day = 2;
var lang = 'en-us';
var weekdaysLegend = [
{'it-it':'Lunedì', 'en-us':'Monday'},
{'it-it':'Martedì', 'en-us':'Tuesday'},
{'it-it':'Mercoledì', 'en-us':'Wednesday'},
{'it-it':'Giovedì', 'en-us':'Thursday'},
{'it-it':'Venerdì', 'en-us':'Friday'},
{'it-it':'Sabato', 'en-us':'Saturday'},
{'it-it':'Domenica', 'en-us':'Sunday'}
];
alert(weekdaysLegend[day][lang]);

Categories