how can i solve javascript variable error ? (let) - javascript

function solution(string, searchValue) {
let answer;
for (let i = 0; i < string.length; i++) {
var count_no_string = 0;
//case 1
if (searchValue[0] == string[i]) {
let save = i;
let count = 0;
for (let j = 0; j < searchValue.length; j++) {
if (searchValue[j] == string[save + j]) {
count = count + 1;
if (searchValue.length == count) {
answer = save;
return answer;
} else{
console.log('f'+ count +' '+ searchValue.length);
}
} else {
console.log('일치하는 문서가 없습니다' );
return -1;
}
}
}
//case2
else if(searchValue[0] != string[i]){
count_no_string = count_no_string+1;
console.log('test ' + count_no_string);
if(count_no_string == string.length){
//retrun -1;
return -1;
}
}
}
}
i don't know why count_no_string variable is always '1'
why?..
i found let, var, const js variable concept, but i can't solve it
thanks you so much
.........
.........
.......
.........

Related

How to increment/decrement variable value only once while in a loop?

I need to decrement var "left" by 1 and only once instead of having it go through a loop and decrement if conditions pass true. But conditions are valid only if they are in a loop. How would I do this?
let key = e.key.toLowerCase()
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
console.log(e.key)
guessed[i] = key
} else {
console.log('This is where i want left--')
}
}
}
left--; //Need this to decrement only once
Store whether left has been decremented in a variable:
let key = e.key.toLowerCase()
let decrementedLeft = false;
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
console.log(e.key)
guessed[i] = key
} else {
if(!decrementedLeft){
decrementedLeft = true;
left--;
}
}
}
}
if(!decrementedLeft){
left--;
}
You can use this method:
key = e.key.toLowerCase()
Let decrement=false;
for (i = 0; i < word.length; i++) {
if(decrement==false)
if (word[i] == key) { if (guessed[i] != key) { console.log(e.key) guessed[i] = key } else { left--;
decrement=true;} } }
Or you can just break out from the loop using break
Due to more conditions I decided so. Thank you for your answers!
As a standard, got myself a few additional problems. Like first if{}else{} in the loop is executing both if and else instead of one or the other... So confusing.
let correct = 0;
let key = e.key.toLowerCase()
for (i = 0; i < word.length; i++) {
if (word[i] == key) {
if (guessed[i] != key) {
guessed[i] = key
correct = 1;
console.log(e.key)
} else {
console.log('Guessing same key')
correct = 1;
}
}
}
if (correct != 1) {
left--;
console.log('Decrementing')
tries.innerHTML += `<span>${key} </span>`
correct = 0
}

No response from recursive function

I want to create a function that is able to determine if a number is same or palindrome. if a given number is palindrome or same then return 2 otherwise if it is not palindrome or same then i need check it twice by increment the given number by 1. after that if it palindrome or same then return 1. if no palindrome or same number found then return 0. i write the function which is giving me the exact result when i give the number as 11211 but the function don't show any response if i enter 1122 or other random value. please help me to find where the error of my function.
function sameOrPalindrome(num) {
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num);
if (al == 2) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
here is my solution to this problem:
function reversedNum(num) {
return (
parseFloat(
num
.toString()
.split('')
.reverse()
.join('')
) * Math.sign(num)
)
}
function sameOrPalindrome(num) {
if (num === reversedNum(num)) {
return 2;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
} else {
num++;
if (num === reversedNum(num)) {
return 1;
}
}
}
return 0;
}
console.log("1233",sameOrPalindrome(1233))
Perhaps not using recurse - I think your function loops
const allEqual = arr => arr.every( v => v === arr[0] )
const sameOrPalin = num => {
const str = String(num);
let arr = str.split("")
if (allEqual(arr)) return 2
arr.reverse();
if (arr.join("") === str) return 1;
return 0
};
console.log("1111",sameOrPalin(1111));
console.log("2111",sameOrPalin(2111));
console.log("2112",sameOrPalin(2112));
console.log("1234",sameOrPalin(1234));
for (let i = 2111; i<=2113; i++) console.log(i,sameOrPalin(i));
Question: I assumed if palindrome test is true at first time then return 2. if not try incrementing by one and test the palindrome again . if true return 1 else try incrementing for last time and check the palindrome if true return 1 else 0.
Store string into array first and do arr.reverse().join("") to compare
let arr=num.toString().split("");
if(num.toString() == arr.reverse().join(""))
function sameOrPalindrome(num, times) {
let arr = num.toString().split("");
if (num.toString() == arr.reverse().join("")) {
if (times == 3) return 2
else return 1;
} else if (times > 0) {
num++; times--;
return sameOrPalindrome(num, times);
} else return 0
}
console.log(sameOrPalindrome(123321, 3));
console.log(sameOrPalindrome(223321, 3));
console.log(sameOrPalindrome(323321, 3));
Your function needs to know if it should not call itself any more, e.g. when it's doing the second and third checks:
function sameOrPalindrome(num,stop) { // <-- added "stop"
var c = 0;
var al = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] != revArray[i]) {
c++;
}
}
if (c == 0) {
return 2;
} else if(!stop) { // <-- check of "stop"
num++;
al = sameOrPalindrome(num,true); // <-- passing true here
if (al == 2) {
return 1;
} else {
num++;
al = sameOrPalindrome(num,true); // <-- and also here
if (al == 2) {
return 1;
}
}
}
return 0;
}
for(let i=8225;i<8230;i++)
console.log(i,sameOrPalindrome(i));
function check_palindrom(num){
var c1 = 0;
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse();
for (var i = 0; i < normalArray.length; i++) {
if (normalArray[i] == revArray[i]) {
c1++;
}
}
if(c1==0){
return 2;
}else{
return 1;
}
}//check_palindrom
function my_fun_check_palindrome(mynum){
//console.log(mynum);
var num = mynum;
var c2 = 0;
var al = 0;
var normalArray = mynum.toString().split("");
var revArray = mynum.toString().split("").reverse();
for (var j = 0; j < normalArray.length; j++) {
if (normalArray[j] == revArray[j]) {
c2++;
}
}
if(c2==0){
console.log('Number is palindrome. Return Value :'+ 2);
}
if(1){
console.log('checking again with incremeting value my one');
num = parseInt(num)+1;
al = check_palindrom(num);
if(al==2){
console.log('Number is palindrome. Return Value :'+ 1);
}else{
console.log('Number is not palindrome. Return Value :'+ 0);
}
}
}//my_fun_check_palindrome
console.log(my_fun_check_palindrome(1122));
console.log(my_fun_check_palindrome(11221));
We should always strive to make function more effiecient... you dont need to run full loop. plus actual checking of palindrome can me modularized
function isSameOrPalindrome(num) {
var normalArray = num.toString().split("");
var revArray = num.toString().split("").reverse(),
i;
for (i = 0; i < normalArray.length / 2; i++) {
if (normalArray[i] !== revArray[i]) {
break;
}
}
if (i >= normalArray.length/2) {
return "Palindrome";
} else {
return "Not Palindrome";
}
}
function doCheck(num) {
var isPalindrome = isSameOrPalindrome(num);
console.log(isPalindrome);
if(isPalindrome === "Palindrome") {
return 2;
} else {
num++;
isPalindrome = isSameOrPalindrome(num);
if(isPalindrome === "Palindrome") {
return 1;
} else {
return 0
}
}
}
console.log("100",doCheck(100));

making custom validation for password field in react

I am making a custom registration page with only 2 values Email and Password, later I will add confirm password as well, for my password field I have some restrictions and I am using some regex and also some custom made code to make the validation.
this is my validateField:
validateField(fieldName, value) {
let fieldValidationErrors = this.state.formErrors;
let emailValid = this.state.emailValid;
let passwordValid = this.state.passwordValid;
//let passwordValidConfirm = this.state.passwordConfirmValid;
switch(fieldName) {
case 'email':
emailValid = value.match(/^([\w.%+-]+)#([\w-]+\.)+([\w]{2,})$/i);
fieldValidationErrors.email = emailValid ? '' : ' is invalid';
break;
case 'password':
passwordValid = (value.length >= 5 && value.length <= 32) && (value.match(/[i,o,l]/) === null) && /^[a-z]+$/.test(value) && this.check4pairs(value) && this.check3InRow(value);
fieldValidationErrors.password = passwordValid ? '': ' is not valid';
break;
default:
break;
}
this.setState({formErrors: fieldValidationErrors,
emailValid: emailValid,
passwordValid: passwordValid,
//passwordValidConfirm: passwordValidConfirm
}, this.validateForm);
}
as you can see for
passwordValid
I have made some methods, this one
check3InRow
doesnt work the way I want it to work, this one makes sure, you have at least 3 letters in your string that are in a row so like "abc" or "bce" or "xyz".
check3InRow(value){
var counter3 = 0;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if((lastC + 1) === value.charCodeAt(i)){
counter3++;
if(counter3 >= 3){
alert(value);
return true;
}
}
else{
counter3 = 0;
}
lastC = value.charCodeAt(i);
}
return false;
}
this doesnt work correctly so it should accept this:
aabcc
as a password but not:
aabbc
You are starting your counter from 0 and looking for greater than equal to 3 which will never be 3 for 3 consecutive characters. Rest everything is fine with your code.
check3InRow(value) {
var counter3 = 1;
var lastC = 0;
for (var i = 0; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
alert(value);
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}
Can we not do a simple version of that function? Like
function check3InRow2(value){
for (var i = 0; i < value.length-2; i++) {
const first = value.charCodeAt(i);
const second = value.charCodeAt(i+1);
const third = value.charCodeAt(i+2);
if(Math.abs(second - first) === 1 && Math.abs(third-second) === 1){
return true;
}
}
return false;
}
I mean complexity wise it is O(N) so maybe we can give this a try
Also adding the your function. When you are AT a char then you should consider counter with 1. Because if another one matches it will be 2 consecutive values.
function check3InRow(value) {
var counter3 = 1;
var lastC = value.charCodeAt(0);
for (var i = 1; i < value.length; i++) {
if ((lastC + 1) === value.charCodeAt(i)) {
counter3++;
if (counter3 >= 3) {
return true;
}
} else {
counter3 = 1;
}
lastC = value.charCodeAt(i);
}
return false;
}

Variable is already defined with local variables? How?

This is my code for checking a register page. It says that variables i and j are already defined, although it's local variables and not global. What could I do in this situation? How can I make the vars locally and not globally? Help is really appreciated, I am a new student in Computer Science.
function checkName() { // בודק על
var n = document.getElementById("FullName").value;
var len = n.length;
var no = "!##$%^&*()-_+=\'|][}{><./,;:?,";
var num = "0123456789";
if (n == "") {
document.getElementById("errName").innerHTML = "רשום את השם בבקשה";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
if (len < 2) {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אות אחת";
return false;
}
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) >= "a" && n.charAt(i) <= "z") {
document.getElementById("errName").innerHTML = "לא הגיוני שם עם אותיות באנגלית";
return false;
}
}
for (var i = 0; i < no.length; i++) {
for (var j = 0; j < n.length; j++) {
if (no.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור תווים מיוחדים";
return false;
}
}
}
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
for (var i = 0; i < 3; i++) {
if (n[i] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
if (n[i + 1] == ' ') {
document.getElementById("errName").innerHTML = "אסור רווחים בהתחלה";
return false;
}
}
}
document.getElementById("errName").innerHTML = "";
return true;
}
Javascript has function scope, so defining any variable in a function with var will make it exist throughout the function.
In each for loop, you redefine i with var i = 0. For example:
for (var i = 0; i < n.length; i++) {
if (n.charAt(i) == " ") {
len--;
}
}
...
for (var i = 0; i < num.length; i++) {
for (var j = 0; j < n.length; j++) {
if (num.charAt(i) == n.charAt(j)) {
document.getElementById("errName").innerHTML = "אסור מספרים";
return false;
}
}
}
You can add a var i; at the top of the function instead, and simply say i=0 in your loops, so you don't define it multiple times.
Consider looking into using let in newer JS versions.
Try to use new ES6 let instead of var to declare a variables in your functions/project.
This will solve your issue with global name scope.
You can read more here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let
You need to look into function scoping. As var has scope of function in which it is defined.
So in your case variable i has access inside checkName function. Using let will help you out in above scenario.

How to reduce time of execution for javascript code

Below is my code which is taking time in the for loop to extract data from one object and filling another object. Is there any way to reduce the time of execution? I have tried a while loop but it is not helping that much. Kindly help
function SetGridWithData(result) {
if (!result) {
return;
}
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (result.length >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
} else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
} else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < result.length; i++) {
boxOfJson.push(result[i]);
}
}
}
I am trying to implement paging which is done, but 100 data per page first it will check page no 0 if it is then loop one and if other than 0 than else case.
You could try caching result.length at the beginning of your function (following the if check at the beginning)..
function SetGridWithData(result) {
if (!result) { return; }
var resultLength = result.length;
CtrlBillableItem_SearhedBillableItems = result
var boxOfJson = [];
var j = 100;
if (resultLength >= 100) {
if (PagingLastRecNum == 0) {
btnPrevious.style.display = 'none';
for (var i = 0; i < j; i++) {
boxOfJson.push(result[i]);
}
}
else {
btnPrevious.style.display = 'inline';
var intializer = (j * PagingLastRecNum) + PagingLastRecNum;
var limiter = intializer + 99;
for (var i = intializer; i < limiter; i++) {
boxOfJson.push(result[i]);
}
}
}
else {
btnPrevious.style.display = 'none';
btnNext.style.display = 'none';
for (var i = 0; i < resultLength; i++) {
boxOfJson.push(result[i]);
}
}
}

Categories

Resources