If Statement Returning True All The Time - javascript

I am trying to check if the input is true, and continue to next word if false.
"Apples",
"Bananas",
"Pears",
"Door",
"Towel",
"Computer",
];
var x = myArray[Math.floor(Math.random()*myArray.length)];
function clearbox(){
if (x = myInput.value){
var x = myArray[Math.floor(Math.random();*myArray.length)]);
document.getElementById('myInput').value = ''
document.getElementById("word").innerHTML = x
} else {
document.getElementById('myInput').value = '' ;
}
};
For some reason the if statment is not working, can someone help please?

Your if statement if (x = myInput.value) should be using a boolean comparison operator (==), but you used an assignment operator (=) instead. As a result, the variable x is being set to the value myInput.value which will always return true, as values > 0 are interpreted to be true by the compiler. Instead, your function should read:
function clearbox(){
if (x == myInput.value){
var x = myArray[Math.floor(Math.random()*myArray.length)]);
document.getElementById('myInput').value = ''
document.getElementById("word").innerHTML = x
} else {
document.getElementById('myInput').value = '' ;
}

You should be using == instead of = which results in true always (you can also use === for type checking as well):
if (x == myInput.value)
You have a syntax error here (remove the ;):
var x = myArray[Math.floor(Math.random()*myArray.length)]);

Related

Check if second string is rotation of another string

I'm trying to write a function that takes in two string parameters and check if the second parameter is a rotated version of the first string.
So the following would be the results:
checkRotationStrings('waterbottle', 'lewaterbott'); // true
checkRotationStrings('waterbottle', 'bottlewater'); // true
checkRotationStrings('waterbottle', 'erbottlewat'); // true
checkRotationStrings('waterbottle', 'lewaterbottx'); // false
I wrote the following code, but there are some edge cases that I can't seem to figure out:
function checkRotationStrings(string, rotatedString) {
let result;
let rotationCheck
let stringArr = string.split('');
let rotatedStringArr = rotatedString.split('')
for (let i = 0; i < string.length - 1; i++) {
if (rotatedString[0] === stringArr[i]) {
result = stringArr.slice(i);
rotationCheck = stringArr.slice(0, i).concat(result).join('');
}
}
console.log(rotationCheck)
if (rotationCheck === string){
return true;
} else {
return false;
}
}
Any help would be appreciated.
You could use String#repeat with rotated and two as parameter and check with String#includes.
function checkRotationStrings(string, rotated) {
return string.length === rotated.length && rotated.repeat(2).includes(string);
}
console.log(checkRotationStrings('waterbottle', 'lewaterbott')); // true
console.log(checkRotationStrings('waterbottle', 'bottlewater')); // true
console.log(checkRotationStrings('waterbottle', 'erbottllewat')); // false
console.log(checkRotationStrings('waterbottle', 'lewaterbottx')); // false
console.log(checkRotationStrings('waterbottle', 'ttlewaterb')); // false
You could use substring and rotate until you find a match. Like this:
function checkRotationStrings(string, rotatedString) {
let match = false;
for (let i = 0;
(i < string.length - 1) & !match; i++) {
match = rotatedString.substring(i, rotatedString.length) + rotatedString.substring(0, i) === string;
}
return match
}
console.log(checkRotationStrings('waterbottle', 'lewaterbott')); // true
console.log(checkRotationStrings('waterbottle', 'bottlewater')); // true
console.log(checkRotationStrings('waterbottle', 'erbottlewat')); // true
console.log(checkRotationStrings('waterbottle', 'lewaterbottx')); // false
This is a somewhat strange solution, as it uses some only for the index parameter. But each iteration in some simply compares two strings, one which is a rotation of the first, and the other is the second one.
const checkRotationStrings = (str, rot) =>
str.split('').some((s, i) => str.slice(i) + str.slice(0, i) == rot);
[
['waterbottle', 'lewaterbott'], // true
['waterbottle', 'bottlewater'], // true
['waterbottle', 'erbottllewat'], // false -- ORIGINAL
['waterbottle', 'erbottlewat'], // true -- CORRECTED
['waterbottle', 'lewaterbottx'] // false
].forEach(([s, r]) => console.log(`'${s}', '${r}': ${checkRotationStrings(s, r)}`))
You can do the following:
checkRotationStrings(str1: string, str2: string) {
if (str1.length !== str2.length) {
return false;
} else {
for (var i = 0; i < str2.length; i++) {
if (str2[i] === str1[0]) {
var substring1 = str2.substring(0,i);
var substring2 = str2.substring(i,str2.length);
var concatWord = substring2.concat(substring1);
if(str1 === concatWord){
console.log(str1 + " matches " + concatWord)
return true;
}else{
console.log(str1 + " not matches " + concatWord)
}
}
}
return false;
}
}
Stack Overflow questions often receive answers in the form of completely new code (and/or ideas) on how to achieve the desired result. Usually, there's at least an attempt to help the questioner with their actual question, which in this case seemed to ask for some help with your code (one issue at least had to do with "slicing," as you commented).
I also love to offer new code or ideas if I particularly like it so I'm only partly critical here, but the answers so far have suffered from a complete lack of relating to the question.
There's nothing wrong with how you have conceived of checking for string rotation. You just have a couple of bugs:
First, since rotationCheck is meant to rotate string in order to compare it with rotatedString, you got the string-building reversed. It should be:
rotationCheck = result.concat(stringArr.slice(0, i)).join('');
Secondly, once you've built the rotation-check, you need to compare it with rotatedString, not string. So:
if (rotationCheck === rotatedString){
I might be late for this, but here is my solution and it include all edge cases.
function checkRotation(str1,str2){
const char0 = str1[0];
let ind = str2.indexOf(char0);
while(ind>-1){
const start = str2.substring(0,ind);
const end = str2.substring(ind,str2.length);
if(end+start === str1){
return true;
}
ind = str2.indexOf(char0,ind+1)
}
return false
}
console.log(checkRotation("assads","adsass"))
Instead of trying to break it in random pieces and do different checks, you could instead do a count of the letters. This would be much simpler:
const countLetters = a => Array.prototype.reduce.call(a, (r, l) => Object.assign(r, { [l]: (r[l] || 0) + 1 }), {});
function checkRotatedString(a, b) {
const countA = countLetters(a);
const countB = countLetters(b);
return Object.keys(countA).length === Object.keys(countB).length
&& Object.entries(countA).every(([key, value]) => value === countB[key]);
}
// Tests
[['waterbottle', 'lewaterbott'], ['waterbottle', 'bottlewater'], ['waterbottle', 'erbottlewat'], ['waterbottle', 'lewaterbottx']]
.forEach(a => console.log(a, checkRotatedString.apply(null, a)));

Javascript run a function against a variable usnig dot notation

I think I'm using the wrong terminology but here is what I would like to do. Using a function like this one:
function isNumeric(){
if (isNaN(this)) { return false; }
var x = parseFloat(this);
return (x | 0) === x;
};
I know this function won't work as is. I removed the parameter that was originally passed in and replaced it inside the function with this. I would like to call it like so:
var tmp1 = 10;
var tmp2 = "10";
if( tmp1.isNumeric() == true && tmp2.isNumeric() == true ){
...
}
Instead of this:
if( isNumeric(tmp1) == true && isNumeric(tmp2) == true ){
...
}
The way to achieve that is not considered a good option, but it's to modify the prototype chain for the types of data you want your function to work with, e.g. for number and string like your example you could have:
Number.prototype.isNumeric = String.prototype.isNumeric = function() {
// ...
}
What you have currently is the preferred option because it won't contaminate the prototype chain for inbuilt types, risk conflicts with other libraries, potentially overwrite functionality you didn't know existed, etc. You could meet halfway with something like:
class Val {
constructor(value) {
this.value = value;
}
isNumeric() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
}
Used like:
var tmp1 = new Val(10);
var tmp2 = new Val('10');
console.log(tmp1.isNumeric(), tmp1.isNumeric());
try to add this function to Object.prototype
Object.prototype.isNumeric = function () {
return parseFloat(this) == this;
};
Below may be a better option for the class function if you are wanting "10" to return that is it not a number.
isNumeric() {
return typeof this.value === 'number';
}
isNumeric is just a function - what you are looking for is an object method. Right now, tmp1 and tmp2 are a Number, and String respectively, and neither of those have a function called isNumeric. You can restructure those variables like this if you want:
function TmpValue (initValue) {
this.value = initValue
}
TmpValue.prototype.isNumeric = function() {
if (isNaN(this.value)) { return false; }
var x = parseFloat(this.value);
return (x | 0) === x;
}
var tmp1 = new TmpValue(10);
var tmp2 = new TmpValue('10');

How To Break Out Of arr.find()?

This might not be best practice, but I was wondering if it's possible to break from the arr.find() method.
Here's some code that I was working on that I've since redone with a loop but I was wondering why this is not allowed?
Any help is appreciated!
I understand this isn't the best approach to the problem at hand I'm just curious to why the break doesn't work as intended where am I messed up in my thinking?
//Using the JavaScript language, have the function SimpleSymbols(str) take the str parameterbeing passed and determine if it is an acceptable sequence by either return in the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
//loop through Array
//Determine if letter is surrounded by +
//If yes continue on and return true
//If no break loop and return false
function SimpleSymbols(str){
str = str.split('');
var pass = null;
function finder(char){
if (char.length === 1 && char.match(/[a-z]/i)){
var firstPlus = str.indexOf(char)- 1;
var secondPlus = str.indexOf(char)+ 1;
console.log(str[firstPlus]);
if (str[firstPlus] === '+' && str[secondPlus] === '+'){
pass = 'true';
} else {
pass = 'false'
break;
}
}
}
str.find(finder);
return pass
}
SimpleSymbols('++d+===+c++==a++q++');
This code will break loop in your case after 5 iterations:
SimpleSymbols('++-+d+===*c+3++==a++q-3++');
function SimpleSymbols(str){
str = str.split('');
var pass = null;
str.find(finder);
function finder(char, i){
console.log('Iteration No.' + i);
if (str.indexOf(char) && char.length === 1 && char.match(/[a-z]/i)){
var firstPlus = str.indexOf(char)- 1;
var secondPlus = str.indexOf(char)+ 1;
//console.log(str[firstPlus]);
if (str[firstPlus] === '+' && str[secondPlus] === '+'){
pass = 'true';
return pass;
} else {
pass = 'false';
}
}
}
console.log('FINAL RESULT = ' + pass);
return pass;
}

Understanding this Javascript function

I am continuing a project. And this is the only thing I do not understand. It is the key function for assembling a filter string to be used for sql query. This function is invoke via onclick of a button.
My problem is the value for query is taken from $_REQUEST['FILTER'].
<input id="HDN_FILTER" name="FILTER" type="hidden" value="<?php echo $_REQUEST['FILTER']; ?>">
At first $_REQUEST['FILTER'] is empty. Then upon pressing the submit button it assembles and return the string. But I don't understand how it assembled the string. Because it seems the function get its value from this input. But it's value is empty. So the function should received empty from this input. It's like going in circles
Example what does "" != means in javascipt anyway?
An example of the assembled string is ""DELIVER_STORE_ACCOUNT=ALL^STORES_ACCOUNT=ALL^ACTIVE=1^PART_NUMBER=ALL^NEW_PART_NUMBER=ALL""
And I see the join("^") part in the function. And it seems this line assembles it. But why is it inside a switch parenthesis?
function SUBMIT(e, t) {
array_Filter = new Array;
for (i in array_Dropdown) {
if (varField = array_Dropdown[i], varID = "SEL_" + varField, aryTemp = new Array, -1 != document.getElementById(varID).selectedIndex)
for (i = 0; i < document.getElementById(varID).options.length; i++)
document.getElementById(varID).options[i].selected === !0 && (aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value);
aryTemp.length > 0 && (array_Filter[varField] = aryTemp)
}
"" != document.getElementById("HDN_SEARCH").value && (aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value), array_Filter_Temp = new Array;
for (i in array_Filter)
array_Filter_Temp[array_Filter_Temp.length] = i + "=" + array_Filter[i].join("|");
switch (varFilter = array_Filter_Temp.join("^"), document.getElementById("HDN_FILTER").value = varFilter, document.getElementById("HDN_EXCEL").value = 1 == e ? 1 : 0, !0) {
case 1 == t:
document.getElementById("HDN_OVERRIDE").value = 1;
break;
case 0 == t:
document.getElementById("HDN_OVERRIDE").value = 0;
break;
case-1 == t:
}
varTXTBOX = document.getElementById("TXT_SEARCH").value;
alert(varTXTBOX);
document.getElementById("FORM1").submit()
}
Whoever wrote this code was trying to obfuscate it, making it hard for anyone else to understand what it does, perhaps because the result is sent to a SQL query, as you stated. Of course, if you want to hide anything from your users, specially SQL commands, implement it server-side.
1) The "" != part:
"" != document.getElementById("HDN_SEARCH").value // left side
&& // logical AND
(aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value), // right side
array_Filter_Temp = new Array; // another statement
Here he's taking advantage of the short-circuit evaluation, if the left side of the expression evaluates to false, then the right side isn't executed. The next statement after the , is always executed (read more about the comma operator). So it's the same as writing:
if (document.getElementById("HDN_SEARCH").value != "") {
aryTemp.SEARCH = document.getElementById("HDN_SEARCH").value
}
array_Filter_Temp = new Array;
2) The switch part:
switch (
varFilter = array_Filter_Temp.join("^"),
document.getElementById("HDN_FILTER").value = varFilter,
document.getElementById("HDN_EXCEL").value = 1 == e ? 1 : 0,
!0
) {
The first two are trivial. On the third one, he is assigning HDN_EXCEL based on the value of e. Adding parenthesis makes it clearer: document.getElementById("HDN_EXCEL").value = (1 == e) ? 1 : 0
The !0 is there just to make sure the rest of the switch is executed (it evaluates to true). If it was 0 or false, then HDN_OVERRIDE would never be assigned to a value.
So that whole set could be rewritten as:
varFilter = array_Filter_Temp.join("^");
document.getElementById("HDN_FILTER").value = varFilter;
document.getElementById("HDN_EXCEL").value = (e == 1) ? 1 : 0;
switch (t) {
case 1:
document.getElementById("HDN_OVERRIDE").value = 1;
break;
case 0:
document.getElementById("HDN_OVERRIDE").value = 0;
break;
}
3) The first for loop: (you haven't asked, but here it goes anyway)
for (i in array_Dropdown) {
if (
varField = array_Dropdown[i],
varID = "SEL_" + varField,
aryTemp = new Array,
-1 != document.getElementById(varID).selectedIndex
)
for (i = 0; i < document.getElementById(varID).options.length; i++)
document.getElementById(varID).options[i].selected === !0 && (aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value);
aryTemp.length > 0 && (array_Filter[varField] = aryTemp)
}
Again the use of the , operator to execute all commands and return the value of the last one to the if, which is -1 != document.getElementById(varID).selectedIndex, so the second for loop will run only if the element in varID has a selectedIndex.
The === !0 is the same as === true.
This could be rewritten as:
for (key in array_Dropdown) {
varField = array_Dropdown[key];
varID = "SEL_" + varField;
aryTemp = new Array;
if (document.getElementById(varID).selectedIndex != -1) {
for (i = 0; i < document.getElementById(varID).options.length; i++) {
if (document.getElementById(varID).options[i].selected) {
aryTemp[aryTemp.length] = document.getElementById(varID).options[i].value;
}
}
}
if (aryTemp.length > 0) {
array_Filter[varField] = aryTemp;
}
}
As a side note, if you can, I suggest you refactor this code, send only the collected data to the server and do all the transformation needed on the server-side.

I have an If statement that is not working, yet is logically correct

if ("tester" == findrange[117])
{
var indict = 34;
}
if (keeperval[39] == "tester")
{
var indict2 = 45;
}
if (keeperval[39] == findrange[117])
{
var indict3 = 56;
}
This code will return when debugging will return these values:
indict = 34
indict2 = 45
indict3 = undefined
Does this make any sense? I just can't wrap my head around why this possibly wouldn't work!
You probably wrapped your strings in findrange[117] and keeperval[39] in String, instead of simply using a literal.
Therefor, both aren't strings, but instead string objects. When you use them in a comparison with strings, it will use the object's .toString(), therefor == "tester" will work.
However, when both sides of an equality comparison are objects, the result will be true if and only if both objects are actually the same:
var s1 = new String("test");
var s2 = new String("test");
console.log(s1 == s2); // logs false
So instead of
findrange[117] = new String("tester");
keeperval[39] = new String("tester");
use
findrange[117] = "tester";
keeperval[39] = "tester";
Even better, exchange your equality tests with type-safe equality tests:
if ("tester" === findrange[117])
{
var indict = 34;
}
if (keeperval[39] === "tester")
{
var indict2 = 45;
}
if (keeperval[39] === findrange[117])
{
var indict3 = 56;
}
Then you will see instantly that there's something off. (fiddle)
For further reference, see MDN's JavaScript guide, especially sameness in JavaScript.
EDIT: If you're not able to change the type of the values in your arrays, use the .toString() method before comparing:
if ("tester" === findrange[117].toString())
{
var indict = 34;
}
if (keeperval[39].toString() === "tester")
{
var indict2 = 45;
}
if (keeperval[39].toString() === findrange[117].toString())
{
var indict3 = 56;
}
use
keeperval[39] === findrange[117]
to understand if both of them are objects or strings.
try groovy console :
def findrange = ["tester","nontester"]
def keeperval = ["tester"]
if ("tester" == findrange[0])
{
def indict = 34;
println indict
}
if (keeperval[0] == "tester")
{
def indict2 = 45;
println indict2
}
if (keeperval[0] == findrange[0])
{
def indict3 = 56;
println indict3
}
output :
34
45
56
First check the type
console.log(typeof(findrange[117]));
In your case this should be an object
In JS,
compare obj to string; will compare obj.value to string value
compare obj to obj; will compare references to the object and not value

Categories

Resources