How to move javascript if conditions to external file? - javascript

Working on a script to transfer data between some software, in this script I have an if condition to ignore some particular fields that do not need to be transferred. Because of this I have a condition that looks something like:
if(
object.field == "_Field1" ||
object.field == "_Field2" ||
object.field == "_Field3" ||
object.field == "_Field4"
...
) { ... }
However there are quite a few of these fields and more will likely emerge so I would like to move these fields to an external (text, or js?) file for easier maintenance and readability, how can I accomplish this without moving the if? Ideally I would like to be able to have another script which will write to this file when it needs to add a new field so the file should be just the comparisons.

you can add the fields that you want to ignore on array and just remove them befor the actual object send:
const ignoredFields=['_Field2','_Field2','_Field3','_Field4']
// or you can read them from a file
const mustIgnore = ({field})=>
return ignoredFields.includes(field)
and now you can use mustIgnore dynamically without changing or adding if statement

You could simply create a function that did this evaluation and returned the result. Something like this:
function isObjectOneOfSpecificFieldSubsets(object) {
return (
object.field == "_Field1" ||
object.field == "_Field2" ||
object.field == "_Field3" ||
object.field == "_Field4"
)
}
Then your code above would become:
if(isObjectOneOfSpecificFieldSubsets(object)) {
...
}

I don't know if I understood your problem well but you could:
have a file that only contains the list of fields you want to check:
const FIELDS = [
"_Field1",
"_Field2",
...
]
have a file with a util:
const doFieldsCheckCondition = (field) => {
...
for (let tmp_field of FIELDS) {
...
}
}
and then use this function in your original script:
if (doFieldsCheckCondition(field)) {...}

Related

Jquery The name '' is does not exists in the current context

Although there are several same questions, I'm very curious regarding this specific case.
jQuery(document).ready(function () {
if ($('#msg').val() != '' && $('#msgSuccess').val() == 'true') {
var msg = $('#msg').val();
var t = $('#msg').val().toString();
toastr.success("#_localizer[t]");
}
});
variable t has some message which represents the key for my localization file.
I have issue to pass that variable (string) to my mvc _localizer.
Where I go wrong with this?
If I add simple console.log(t) it works. So Im guessing that is the localizer is a problem.
I'm using #inject IViewLocalizer _localizer from AspNetCore.Mvc.Localization

Javascript data mapping

Can someone explain to me how can I implement in a clean way a solution to get a status (string) from combining two other ones?
I need to declare a function which takes two params (two strings) and needs to return another one based on the combination of those two strings.
For ex:
carStatus(status, secondaryStatus) => string
where secondaryStatus can have multiple options.
I'm thinking using an if/else if statement which returns a third status which I need.
For ex when status is 'OPEN' and secondaryStatus is 'payment1' or 'payment2' or 'payment3', the function must return a new string (status) like 'CONFIRMED'.
So, an example of how I'm thinking to implement at this moment would be something like this:
carStatus = (status, secondaryStatus) => {
if(status === 'OPEN' && (secondaryStatus === 'payment1' || 'payment2' || 'payment3')){
return 'CONFIRMED';
} else if(status === 'CANCELLED' && (secondaryStatus === 'payment4' || 'payment5' || 'payment6')){
return 'REMOVED';
} else if(status === 'REVIEW' && (secondaryStatus === 'payment2' || 'payment5' || 'payment5')){
return 'CHECKED';
}
}
<div>carStatus('OPEN', 'payment1')</div>
In div must be rendered 'CONFIRMED'.
In my implementation, I'll have to write I think other 5 else if statements.. so maybe there is a cleaner way to implement this.
My project is written in React, but I'm thinking to put this function in utils folder. Perhaps a solution written in React could be more clean? I don't know.
Any help will be appreciated.
You can probably use a lookup object for the various options. Since criteria given is very vague following is a very basic example
const carStatus = (carState, carSecondaryState) => {
const secondaries = {
ORDERED: 'CLIENT'
}
return `${secondaries[carSecondaryState]}_${carState}`
}
console.log(carStatus('NEW', 'ORDERED'))

How to load one of many external JS arrays and reference the variable in specific external JS file

I apologise in advance if this question is repeated elsewhere. I am at a loss as to how to correctly phrase the question to find the answer through research alone.
I have many external js files which each contain a js array. I can reference these files and pull them into my webpage easily enough, but accessing the array via a placeholder isn't working. If the file is named 'walberton.js' the array it contains is named 'walberton'.
myBoundary = 'walberton'
The following works as the placeholder for the array is implicitly stated (walbertonx):
function showHideBoundary(myBoundary) {
var boundarySourceFile = myBoundary + '.js';
if (typeof walbertonx == 'undefined') {
var poll;
var timeout = 100; // 10 seconds timeout
var s = document.createElement("script");
s.src = boundarySourceFile;
document.body.appendChild(s);
poll = function () {
setTimeout(function () {
timeout--;
if (typeof walbertonx !== 'undefined') {
// External file loaded
drawWSCountyBoundary(walbertonx);
} else if (timeout > 0) {
poll();
} else {
// External library failed to load
alert("Apologies. Unable to load Boundary at this time.");
}
}, 100);
};
poll();
} else if (walbertonx !== undefined && line === undefined && line.getMap() === null) {
drawWSCountyBoundary(walbertonx);
} else if (walbertonx !== undefined && line !== undefined && line.getMap() !== null) {
line.setMap(null);
} else {
line.setMap(map);
}
}
The idea is code-reuse for all 163 boundary files I have. So, in the same way as I can reference the file with myBoundary, I can replace walbertonx with the actual variable once it has successfully loaded. The trick is I need to know what to check for before it's loaded and once it's loaded use that rather than the placeholder.
Code in the global scope should be accessible to all files loaded after it. Ensure that you include your 'walberton.js' file first. Afterwards you should be able to access the array granted it's in the global scope.
You could also attach the array to the window object if that suits your fancy, like so:
Window.walberton = walberton
Then you can access it in your secondary file like this
alert(Window.walberton)
If it is that you want to dynamically add them, consider having a global object array on the window
Window.fileArrays['walberton'] = walberton
Window.fileArrays['other'] = other
You'd ensure you do this in each file where you want to add an array.
Then you can iterate over them. Just ensure you detach them from the window when you're done.

Parsing JSON into an object with a defined 'schema'

I have a user specified JSON object that I'm attempting to process in the browser.
The problem is that it needs to match an existing object.
They can't accidentally:
forget to include some fields.
typo fields or deliberately add new fields.
Is there a way to handle this?
so basically if I have an object with foo and bar members, I want their defaults if the user's json is just {} ... and if they accidentally send something like {bart: "asdf";} (typo on 'bar') then I want it to generate an exception.
var default_object = { ... };
var allowed_keys = [ "key1", "key2", ... ];
var new_object = default_object.clone();
for (var key in json_object) {
if (json_object.hasOwnProperty(key)) {
if (allowed_keys.indexOf(key) == -1) {
// Report error here
} else {
new_object[key] = json_object[key];
}
}
}
See here for how to write the clone method I used above. If you use jQuery, you could simplify some of this code by using $.extend().

How to validate data with usage logic in Azure mobile service

My problem is how do I validate data. I don't know JS, so I tried do in this way:
function insert(item, user, request) {
if(typeof item.NamePlayer!=='empty') // in app default value is 'empty'
{
request.execute();
}
}
Does JS have a contain method on a table? For example I want a response to table 'NamePlayer' and not add an item with the same value.
Your condition will always be true. The operator typeof will return one of the following values: "number," "string," "boolean," "object," "function," and "undefined." - so it will never be "empty". If you want to check whether the item.NamePlayer is not empty, you can use the condition below:
if (item.NamePlayer !== '') {
// ...
}
You can also simplify the condition, which will also catch the case where the client didn't send a NamePlayer value in the input:
if (item.NamePlayer) {
// ...
}
One more thing: your script will only dealing with the "positive" case; it also needs to send a response in case the condition fails. Something like the code below:
function insert(item, user, request) {
if (item.NamePlayer) {
request.execute();
} else {
request.respond(400, 'NamePlayer is required');
}
}

Categories

Resources