Which three-values would you choose for a "javascript enum"? - javascript

In JavaScript, I'm building something like tic-tac-toe (but more complex). Any given field can have three values: a black piece, a white piece or nothing. What would you use to represent these values? Considering you're gonna be passing around about 300+ at a time.
I was first thinking of 'B', 'W' and 'N'. Then I thought of 0, 1 and 2 and now I'm thinking about true, false and null. Which is the better option as far as JavaScript is concerned? Faster? More idiomatic?

It is not going to make a speed difference.
Personally, I'd go with 0,1,2.
In general, I'd avoid making a difference between undefined, null and false. That will just result in some mistakes in a conditional somewhere. In your case, undefined seems a pretty poor choice anyway, because the contents of the field are not undefined/unknown, it is well-defined to be empty.

As Thilo points out you'd want to avoid having multiple values that can make the statement if(position) evaluate position as true. I'd probably go with using null as the empty value, though, as it seems to make more sense to me.
For the other values, I'd definitely go with something that it's hard to mix up. Strings aren't great, because you're going to wind up using B instead of W somewhere along the line and get annoying errors, so 1 and 2 probably aren't bad options.
Another option, though, is to make your own "enum" for the purposes - just have var black = new Object() and var white = new Object() and use those. That way it's a bit more clear what you're referring to than just 1 and 2. Much of a muchness, though.

Related

What is the main difference between these two loops as a solution to this exercise? (learning javascript)

I am learning JS and came across this exercise:
Write a loop which prompts for a number greater than 100.
If the visitor enters another number – ask them to input again.
The loop must ask for a number until either the visitor enters a number greater than 100 or
cancels the input/enters an empty line.
Here we can assume that the visitor only inputs numbers.
There’s no need to implement a special handling for a non-numeric input in this task.
My solution works and was as follows:
let value;
while (true) {
value = prompt('Enter a number greater than 100', 0);
if (value > 100 || value === '');
console.log(value);
break;
}
The MDN solution was this, and though it is shorter and more simple, it seems to accomplish the same task.
let num;
do {
num = prompt("Enter a number greater than 100?", 0);
} while (num <= 100 && num);
Is my solution still valid? Is the MDN one more proper?
I just want to make sure I am understanding things correctly as I go.
If your solution worked before, I think you probably typed in your solution incorrectly here. I am going to assume you meant to write:
if (value > 100 || value === '') {
console.log(value);
break;
}
Since you're just starting out with JS, you will eventually learn that there will be multiple ways you can handle any given coding problem. It will not always be a good answer/wrong answer type of scenario. Sometimes there are multiple ways to accomplish the same thing.
In this example, the MSN solution is better in terms of readability and possibly safety.
The MSN solution creates a while loop with the exit condition identified in the while statement. This loop will exit when that condition is met.
In your solution, the loop will never exit on it's own, the while() statement will always evaluate to 'true'. This loop needs an explicit exit statement, which you provide with the if() condition.
Your method, although it works, is a little bit less safe in terms of code readability and overall maintenance profile. For example, a future developer could by mistake change the if() condition and inadvertently create a never ending loop.
Or, if the loop contained several dozen lines of code, a developer may miss the if condition, and may add some important code after the if condition (such code would not execute when the exit condition is met.)
Yes, this specific sample exercise is trivial, so the code complexity and readability may not matter. But in large enterprise applications with hundreds of lines of code, such code choices carry serious risks with costly implications.
That said, I'll reiterate - as you learn more about JS, you will often find that there are multiple ways of solving any given problem. Sometimes you do want to create an explicit exit condition through an if() statement, on rare occasions you will want to create a never ending loop.
As you explore more complex problems, you will find needs for such solutiosn. So keep learning, keep trying different solutions, and keep asking questions.

Botpress concatenate variable, as argument, in execute code action form

I know if I pass {{variable}} (like a {{event.text}}) in args field of action form works fine.
But, when I try concatenate this variable with a another String, this not work.
Result in {{state.api_url}}/users string, and I need http//myapi.com/users
Is it possible?
I may have an extremely kludgy workaround for this based on bad javascript.
I was looking to iterate a temp variable downwards. I did the assignment in the raw code box for a transition
Good code like temp.variable==1 would be a true/false test.
But just using one equals sign performs the assignment.
So temp.variable=temp.variable-1 in the raw code box subtracted one from my (numeric value) variable.
This seems to return False for the purposes of the transition so it doesn't matter where you point it as long as it's in the chain.
It seems to work for me, anyway.
I'm properly not sure what your code would look like, perhaps you make a new variable then do a transition with
temp.variable_you_just_made=state.api_url+'/users'
then call that variable doing your url thing?
[Looking around I come to suspect the correct thing would be to make a new action https://botpress.io/docs/10.0/getting_started/trivia_actions/ but I am new to all this]

js math equation mystery

I'm new here :)
So, in javascript, I "simply" wanted to solve X in an equation:
My original formula was:
var X = (((((k/(cc**ci))-bk*)/(0.01*kg))-18)/((0.1+0.05*d1)*(280/(w+100)))-sd)
If I recall correctly, it returned some ridiculously high number...
Ok, I guess that was one problem... so, I tried this:
var X = (((((k*1.0/(cc*1.0*ci*1.0))-bk*1.0)/(0.01*kg*1.0))-18)/((0.1+0.05*d1*1.0)*(280/(w*1.0+100)))-sd*1.0)
Now it worked quite well for these simple variables:
cc=0, ci=0, bk=100, kg=100, d1=10, w=100, sd=10
BUT.. when the solution was approaching 0, it suddenly went completely crazy.
In this case, if k=126.4 the solution should be 0. However, I'm getting "7.1054273576" instead. I calculated it with different programs (even my old pocket-calculator lol), and they all say it's 0 --> so I guess my equation should be correct.
I tried k=126.5, which returns 0.119.
and k=126.3, which returns -0.119
These are correct.
So logically k=126.4 should return 0... but it doesn't. It still returns 7.1(...) instead.
I even tried replacing all the variables with the (see above) numbers:
var X = (((((126.4*1/(1*1*1*1))-100*1)/(0.01*100*1))-18)/((0.1+0.05*10*1)*(280/(100*1+100)))-10)
--> THIS STILL RETURNS TO 7.1(...), although it should be 0.
So the problem is definitely not one of my variables.
For these tests I was using an input type="number" object to review the results, if that is of any relevance...
I still can't see the problem, this seems absolutely illogical and is a complete mystery to me. Pls help!
You missed the bit at the end. X is equal to:
7.105427357601002e-15
^
Scientific Notation!
Note the e-15 at the end. That means, in decimal notation, it's
0.000000000000007105427357601002
Or in other words, very close to 0, as far as most uses are concerned. The difference between it and 0 likely comes about by rounding.
The problem was indeed an e-15 at the end. So if anybody else is stumbling across this page they can stop wondering.
A very simple solution: Just use Math.round() in this case to reduce the number of integers behind the comma, so that "e" doesn't get used to describe the number.

Getting an enum from backend and use it as a string in javascript

Today I had a rather heathed discussion with a java backend developer. I do the frontend side with jsangular. His rest service sends me an object that includes an enum. I get this as a string and need to show it in an angular grid.
The enums are very self explainable.
Examples what I get:
Person = {gender: "MAN", position: "IS_EMPLOYED"}
In the view I have to show the following:
man is employed
So i solved it in a simple and generic way:
Person.gender.toLowerCase () + ' ' + Person.position.toLowerCase ().replace ('_', ' ')
He found this terrible programming and demanded that I would make a mapper with if else or switch
So: If(Person.gender==="MAN") return "man"
Else if....
The label name is always the same as the enum name (only lower case and space instead of underscore)
He went on a rampage that it was bad coding and basically terrible and a sin against god...
So my question is this bad/good practice (so a b/w story) or rather acceptable and defendable in some cases?
Typed on my phone so I couldn't put the code examples in the right tags..
There are a few ways to look at this:
Mapping is more robust:
He is right in saying that there should be a complete mapping function. This allows you to handle errors (i.e. if the response you get for position is "banana", you should probably not just throw that out there). This is especially important in backend development when you are probably working with a strict schema.
Scale Matters:
There is nothing technically wrong with your approach. If there are a small number of entries or if the user base or application scope is small, it may not matter much. It doesn't really conform to best practices, but it works, and if that is all that matters, it might be enough. Although you should always strive for best practices, you need to keep the big picture in mind.
Efficiency:
One approach may be more efficient than the other. The difference may be negligible. In web dev, speed is a priority, and if both approaches get the same result but one is much faster, choose that one.
It'd probably be a better idea to make a client-enum map - then just send back the actual value. So you could have:
var personTypes: {
"1": "Is Employed",
..
}
Then simply send 1 back as the enum and use the lookup object:
console.log("Person status: " + personTypes[Person.position]);
Which also makes it easier to display a list of types - pick a new one, and simply send the enum back:
<select ng-model="personTypeEnum" ng-options="enum as type for (enum, type) in personTypes"></select>
Check in your console with printing object.
example if object is person then if you are rendering this object as json, gender(enum) would be as
{"success":true,"person":[{"class":"person","id":26,"comment":null,"gender":{"enumType":"com.project.Person$Gender","name":"MEN"},
so u can print person.gender.name, which will give MEN

I can't figure out the bug in this jQuery

The page having problems is...
http://schnell.dreamhosters.com/index.php?page=gallery#
I use Firebug to debug my jQuery and other code tidbits and it's been proving very useful for Javascript/jQuery debugging. However, at the same time, it's been one of the most frustrating debugging experiences I've ever gone through. I'm not sure why but sometimes it seems like I can copy someone else's methodology from a tutorial, character for character, and yet still come up with errors.
In any case, the problem here is that Firebug claims there is a bug on line 20 of the source.
missing : after property id
[Break on this error] $('#table').animate({"left: " + attr + "px"}, 2000);\n
This bug seems like a huge load to me because the colon is right there! And this is why debugging jQuery/Javascript is such a pain sometimes. The error messages are rather convoluted and sometimes don't even make a lick of sense to me. Or maybe that's just Firebug.
Either way, the goal I'm going for here is that I'm trying to dynamically change the animate function such that the more you click the left arrow, the further left the grid of images is shifted (due to the nature of the CSS 'left' property). I have Javascript variables and a hidden input tag to help hold essential values, but the major hurdle is getting the animate function to recognize these variables. Near as I can tell it will only accept string literals for arguments on how to animate and the documentation doesn't help me because it doesn't discuss the use of variables with animate, as if it's impossible.
Well, let's just say I don't like impossible, he likes to get in my way a lot.
The object literal passed to the animate function is not well formed, it should be:
$('#table').animate({left: attr + "px"}, 2000);
Edit: Looking closely to your code, you are also trying to get a value from an input with id = "count", and you have a missing # character to have an ID selector:
var count = +$('#count').val(); // get #count value as Number
You are also incrementing this count variable, but you should first convert it to Number, because the value attribute of input elements are string. (I did it using the unary plus operator on the right-hand side of the assignment).
You have to convert it to a number, because if you add two variables and one of them is a string, concatenation will take place:
"1" + 1 == "11"
Try:
$('#table').animate({left: attr}, 2000);
The "px" units of measurement here aren't necessary. That aside, the above is the correct creation of an anonymous object. You were just putting a string inside curly braces.

Categories

Resources