Appropriate way to check if 4 strings are duplicated in JS [duplicate] - javascript

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...

Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))

Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});

The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

Related

Merging two comparisons with a common variable together

I have a function as follows:
bullets.forEach(function (b) {
ships.forEach (function (s) {
if (b.x1 >= s.x1 && b.x1 <= s.x2 && b.y1 >= s.y1 && b.y2 <= s.y2) {
animationBucket = animationBucket.filter((i) => {
return (i != b && i != s);
}
);
I want to merge those comparisons which use the same variables like i != b && i != s. I want it to be like i is not equal to b and s using i a single time. Is it possible? If yes, then how?
Edit: I will not be using the same inequality operator all the time. I want a code that should work for all comparisons like, i < j && i > k, i == b && i != s and so on. To be simple, I just want to make the variable (here i ) used two times (or more) to be used only once or maybe in shorter way.
Not exactly, but you can do something like:
return ![b, s].includes(i);
There are not such things in JavaScript yet. But, maybe this may be added in future :) Till that you can use some helper functions to do your tasks.

I am trying to get 3 conditions in one if . But it's not working

I need to match three conditions so that the page can show the appropriate result for that filters. I tried adding the && between three of the conditions but it doesn't work.
I am not revealing the real code here, but I've shown it without the original var names.
if(localStorage.getItem("eg1") == 30000 && eg2 == 1 && eg3 == use){};
eg2 and eg3 are just variables, they are not localstorage.
It should be:
if((localStorage.getItem("eg1") == 30000) && (eg2 == 1) &&
(eg3== use)){};
Here is a bit cleaner way to do it:
const a = ["eg1", "eg2", "eg3"].map(e => localStorage.getItem(e));
if (a[0] == 30000 && a[1] == 1 && a[2] == use) {
//
}
And a less dynamic but shorter way to do it:
if ([30000, 1, use].map((e, i) => e == localStorage.getItem("eg" + i++)).includes(false)) {
}
Try to decompose the problem in order to analyze it better:
var e1 = localStorage.getItem("eg1") === 30000;
var e2 = eg2 === 1;
var e3 = eg3 === use;
I've used triple equal since i suppose you don't want type coercion.
Since you can't show the original code, if you don't put some log of your results it's quite difficult to imagine what variables can contain with appropriate level of certainty.
Sure is that looking to your conditions independently should help you to identify where your guesses fall to fix what appears as a simple branch condition.
localStorage.getItem returns the value as string.
Try using if(localStorage.getItem("eg1") == "30000" && eg2 == 1 && eg3 == use){};

If-causes with boolean in javascript (Beginners)

Is there a possibility to write this "If" more efficient?
if((text.val(“Hello“) == false)&& (text.val(“This“) == true)&&(text.val(“Is“) == false)&&(text).val(“Me“) == false))
{
text = "This"
}
This “if“ should check, whether a value is set true or not. It should display only the “true“ one. If I make it in this way, I have to make a lot of If’s in order to have all possibilities. Is there a way to make it more efficient and better? In database all values are boolean.
To test for one of multiple conditions you could use:
var txt = text.val();
switch(txt){
case "Hello":
case "This":
case "Is":
case "Me":
case "Whatever Else":
text.val("This");
break;
}
This will allow you to test very simply for multiple conditions and respond accordingly. In this case it will return true is any of these conditions are true. To require all would be:
if (txt=="This" && txt=="Hello" && txt=="Is" && txt=="Me"){...}
This is the only way to test that all conditions are true, unless you want to use arrays and a true-false marker.
I think you might be confused as to how .val() works. If the parameter is left empty, it returns the value. If it has a parameter, it sets the value. (jQuery API Documentation) If I read your if statement correctly, it will only execute if the value of the text is equal to "This". This could be simplified by the following:
if(text.val() == “This“) {
text.val("This");
}
In case you wanted your statement rewritten, here is how it might look:
if((text.val() != “Hello“) && (text.val() == “This“) && (text.val() != “Is“) && (text).val() != “Me“))
{
text.val("This");
}
I would also recommend looking through the documentation in link above and even looking through W3Schools.com
This is an efficient way without jQuery or other library:
var text = "Hello This Is Me";
var textSplit = text.split(' ');
var count = textSplit.length;
for(i=0;i<=count;i++){
if(textSplit[i] == 'This'){
text = 'This';
alert(text);
break;
}
}

Can you compare multiple variables to see if they all equal the same value in JS?

Working in Javascript, I am trying to see if 5 different variables all contain the same value at a given time. The value could be 1 of 6 things, but I need to see if they are all the same regardless of which value it is. I have tried this:
if (die1 == die2 & die1 == die3 & die1 == die4 & die1 == die5) {
yahtzeeQualify == true;
}
and this:
if (die1 == die2 == die3 == die4 == die5) {
yahtzeeQualify == true;
}
Are either of these valid? If so, there is probably an error in my code somewhere else...if not, I'd really appreciate some help. I also have these variables in an array called dieArray as follows:
var dieArray = [die1, die2, die3, die4, die5];
It would be cool to learn a way to do this via the array, but if that isn't logical then so be it. I'll keep trying to think of a way on my own, but up until now I've been stuck...
Are either of these valid?
They are "valid" (as in this is executable code) but they don't perform the computation you want. You want to use a logical AND (&&) not a bitwise AND.
The second one is just wrong. You run into type coercion issues and end up comparing die1 to either true or false.
It would be cool to learn a way to do this via the array
You can use Array#every and compare whether each element is equal to the first one:
if (dieArray.every(function(v) { return v === dieArray[0]; }))
// arrow functions make this nicer:
// if (dieArray.every(v => v === dieArray[0]))
Solution with the Array.reduce:
var values = [die1, die2, die3, die4, die5];
var yahtzeeQualify = values.reduce(function(memo, element) {
return element === values[0];
});
The 1st one is what you want, but it's messed up. You want && not &
The 2nd one is logically wrong.
To do it with an array
yahtzeeQualify = dieArray.every(function(n){ return n === dieArray[0] })

Finding in a predefined set of text options

Say, I want to see if a DOM element is a block. I can write it in three ways, depending on my mood:
// first way
if (el.currentStyle.display == "block" || el.currentStyle.display == "inline-block" || el.currentStyle.display == "table-cell")
// second way
var blocks = {"block": 1, "inline-block": 1, "table-cell": 1};
if (el.currentStyle.display in blocks)//
// third way
if (el.currentStyle.display.match(/block|inline-block|table-cell/))
I have mixed feeling about all of them. First is too verbose once I have more than one option. Second contains those arbitrary values in the object (where I put 1s this time). Third looks like overkill. (What exactly is bad about overkilling?)
Do you know another, better way? If no, any cons I am missing about these three ways?
Javascript only, please.
I like the third way; I don't think it looks like overkill at all. If you need an even shorter way then this works too:
el.currentStyle.display.match(/(e-)?(block|cell)/)
But that's not very readable...
It might be worth abstracting it all away by extending the String prototype:
String.prototype.matches = function(what) {
return (',' + what + ',').indexOf(',' + this + ',') > -1;
};
// Using it:
el.currentStyle.display.matches('block,inline-block,table-cell');
If we're primarily aiming for readability, and if this is happening more than once -- perhaps even if it is just once -- I'd move the test to a function. Then define that function whichever way you like -- probably option 1, for max simplicity there.
Overkill? Possibly. But a gift to the programmer who wants to scan and understand the code 6 months from now. Probably you :-)
function isBlock(el) {
return (el.currentStyle.display == "block" ||
el.currentStyle.display == "inline-block" ||
el.currentStyle.display == "table-cell");
}
// ...
if (isBlock(el)) {
// do something
}
Can't you use the 2nd way but check if it's undefined and then skip the ": 1" part. I haven't tested though.
It looks like you need an inArray function, here is one from the top search result:
Array.prototype.inArray = function (value) {
var i;
for (i=0; i < this.length; i++) {
if (this[i] === value) {
return true;
}
}
return false;
};
Then the forth way would look like this:
if (['block','inline-block','table-cell'].inArray(el.currentStyle.display))
Or in a more readable manner:
var isBlock = ['block','inline-block','table-cell'].inArray(el.currentStyle.display);
My prefered solution for this is:
'block||inline-block||table-cell'.indexOf( el.currentStyle.display ) >= 0
I think that this will use native code of the string and be way more efficient than the array & iteration method.

Categories

Resources