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));
Related
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
I want to query object from Parse DB through javascript, that has only 1 of some specific relation object. How can this criteria be achieved?
So I tried something like this, the equalTo() acts as a "contains" and it's not what I'm looking for, my code so far, which doesn't work:
var query = new Parse.Query("Item");
query.equalTo("relatedItems", someItem);
query.lessThan("relatedItems", 2);
It seems Parse do not provide a easy way to do this.
Without any other fields, if you know all the items then you could do the following:
var innerQuery = new Parse.Query('Item');
innerQuery.containedIn('relatedItems', [all items except someItem]);
var query = new Parse.Query('Item');
query.equalTo('relatedItems', someItem);
query.doesNotMatchKeyInQuery('objectId', 'objectId', innerQuery);
...
Otherwise, you might need to get all records and do filtering.
Update
Because of the data type relation, there are no ways to include the relation content into the results, you need to do another query to get the relation content.
The workaround might add a itemCount column and keep it updated whenever the item relation is modified and do:
query.equalTo('relatedItems', someItem);
query.equalTo('itemCount', 1);
There are a couple of ways you could do this.
I'm working on a project now where I have cells composed of users.
I currently have an afterSave trigger that does this:
const count = await cell.relation("members").query().count();
cell.put("memberCount",count);
This works pretty well.
There are other ways that I've considered in theory, but I've not used
them yet.
The right way would be to hack the ability to use select with dot
notation to grab a virtual field called relatedItems.length in the
query, but that would probably only work for me because I use PostGres
... mongo seems to be extremely limited in its ability to do this sort
of thing, which is why I would never make a database out of blobs of
json in the first place.
You could do a similar thing with an afterFind trigger. I'm experimenting with that now. I'm not sure if it will confuse
parse to get an attribute back which does not exist in its schema, but
I'll find out, by the end of today. I have found that if I jam an artificial attribute into the objects in the trigger, they are returned
along with the other data. What I'm not sure about is whether Parse will decide that the object is dirty, or, worse, decide that I'm creating a new attribute and store it to the database ... which could be filtered out with a beforeSave trigger, but not until after the data had all been sent to the cloud.
There is also a place where i had to do several queries from several
tables, and would have ended up with a lot of redundant data. So I wrote a cloud function which did the queries, and then returned a couple of lists of objects, and a few lists of objectId strings which
served as indexes. This worked pretty well for me. And tracking the
last load time and sending it back when I needed up update my data allowed me to limit myself to objects which had changed since my last query.
I have a scenario on my web application and I would like suggestions on how I could better design it.
I have to steps on my application: Collection and Analysis.
When there is a collection happening, the user needs to keep informed that this collection is going on, and the same with the analysis. The system also shows the 10 last collection and analysis performed by the user.
When the user is interacting with the system, the collections and analysis in progress (and, therefore, the last collections/analysis) keep changing very frequently. So, after considering different ways of storing these informations in order to display them properly, as they are so dynamic, I chose to use HTML5's localStorage, and I am doing everything with JavaScript.
Here is how they are stored:
Collection in Progress: (set by a function called addItem that receives ITEMNAME)
Key: c_ITEMNAME_Storage
Value: c_ITEMNAME
Collection Finished or Error: (set by a function called editItem that also receives ITEMNAME and changes the value of the corresponding key)
Key: c_ITEMNAME_Storage
Value: c_Finished_ITEMNAME or c_Error_ITEMNAME
Collection in the 10 last Collections (set by a function called addItemLastCollections that receives ITEMNAME and prepares the key with the current date and time)
Key: ORDERNUMBER_c_ITEMNAME_DATE_TIME
Value: c_ITEMNAME
Note: The order number is from 0 to 9, and when each collection finishes, it receives the number 0. At the same time, the number 9 is deleted when the addItemLastCollections function is called.
For the analysis is pretty much the same, the only thing that changes is that the "c" becomes an "a".
Anyway, I guess you understood the idea, but if anything is unclear, let me know.
What I want is opinions and suggestions of other approaches, as I am considering this inefficient and impractical, even though it is working fine. I want something easily maintained. I think that sticking with localStorage is probably the best, but not this way. I am not very familiar with the use of Design Patterns in JavaScript, although I use some of them very frequently in Java. If anyone can give me a hand with that, it would be good.
EDIT:
It is a bit hard even for me to explain exactly why I feel it is inefficient. I guess the main reason is because for each case (Progress, Finished, Error, Last Collections) I have to call a method and modify the String (adding underline and more information), and for me to access any data (let's say, the name or the date) of each one of them I need to test to see which case is it and then keep using split( _ ). I know this is not very straightforward but I guess that this whole approach could be better designed. As I am working alone on this part of the software, I don't have anyone that I can discuss things with, so I thought here would be a good place to exchange ideas :)
Thanks in advance!
Not exactly sure what you are looking for. Generally I use localStorage just to store stringified versions of objects that fit my application. Rather than setting up all sorts of different keys for each variable within localStore, I just dump stringified versions of my object into one key in localStorage. That way the data is the same structure whether it comes from server as JSON or I pull it from local.
You can quickly save or retrieve deeply nested objects/arrays using JSON.stringify( object) and JSON.parse( 'string from store');
Example:
My App Object as sent from server as JSON( I realize this isn't proper quoted JSON)
var data={ foo: {bar:[1,2,3], baz:[4,5,6,7]},
foo2: {bar:[1,2,3], baz:[4,5,6,7]}
}
saveObjLocal( 'app_analysis', data);
function saveObjLocal( key, obj){
localStorage.set( key, JSON.stringify(obj)
}
function getlocalObj( key){
return JSON.parse( localStorage.get(key) );
}
var analysisObj= =getlocalObj('app_analysis');
alert( analysisObj.foo.bar[2])
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.
I have a pretty big array of JSON objects (its a music library with properties like artist, album etc, feeding a jqgrid with loadonce=true) and I want to implement lucene-like (google-like) query through whole set - but locally, i.e. in the browser, without communication with web server. Are there any javascript frameworks that will help me?
Go through your records, to create a one time index by combining all search
able fields in a single string field called index.
Store these indexed records in an Array.
Partition the Array on index .. like all a's in one array and so on.
Use the javascript function indexOf() against the index to match the query entered by the user and find records from the partitioned Array.
That was the easy part but, it will support all simple queries in a very efficient manner because the index does not have to be re-created for every query and indexOf operation is very efficient. I have used it for searching up to 2000 records. I used a pre-sorted Array. Actually, that's how Gmail and yahoo mail work. They store your contacts on browser in a pre-sorted array with an index that allows you to see the contact names as you type.
This also gives you a base to build on. Now you can write an advanced query parsing logic on top of it. For example, to support a few simple conditional keywords like - AND OR NOT, will take about 20-30 lines of custom JavaScript code. Or you can find a JS library that will do the parsing for you the way Lucene does.
For a reference implementation of above logic, take a look at how ZmContactList.js sorts and searches the contacts for autocomplete.
You might want to check FullProof, it does exactly that:
https://github.com/reyesr/fullproof
Have you tried CouchDB?
Edit:
How about something along these lines (also see http://jsfiddle.net/7tV3A/1/):
var filtered_collection = [];
var query = 'foo';
$.each(collection, function(i,e){
$.each(e, function(ii, el){
if (el == query) {
filtered_collection.push(e);
}
});
});
The (el == query) part of course could/should be modified to allow more flexible search patterns than exact match.