Can a JavaScript loop, upon the second iteration, iterate from the result of the prior iteration?

I just joined Stack Overflow and this is my first post so please do not hesitate to let me know if I am doing anything wrong.

I was presented with a challenge to create a function that accepts a string and calls another given function which swaps indices until the string is returned backwards.

I have gotten as far as below:

//given function
function swap(str, first, last){
    str = str.split('');
    let firstIndex = str[first];    
    str[first] = str[last];
    str[last] = firstIndex;
    str = str.join("").toString()
    return str;
}

//my function
let word = "Hello"
function reverseSwap(str) {
  let result = ""
  for (let i = 0; i < str.length/2; i++) {
  result += swap(str, i, str.length -1 - i);
  }
  return result;
}
console.log(reverseSwap(word))

This however returns “oellHHlleoHello”, because each iteration swaps indices from the original string then concatenates. Is it possible, upon the second iteration, to have the loop iterate from the result of the prior iteration so the following occurs?:

result of first iteration: swap(word, 0, 4) which returns “oellH”
second iteration uses “oellH” instead of “Hello” to swap(1, 3) which returns “olleH”
Then, swap(2,2) which doesn’t change anything.

Why is my transition time not being applied?

I am pushing each raindrop into rainDropArray, then I thought to call a function within the rainDropInterval, hmm(), and Im getting the transformation, just not the timed transition.

var rainDropArray = []; 
var rainDrop;
var randomDrop;
var yourTankOverThere;
var a=0;    
var rainDropInterval = setInterval(function(){

randomDrop = Math.floor(Math.random()*1000);    
rainDrop = 
document.createElement('div');
document.body.appendChild(rainDrop);rainDrop.style='box- 
sizing:border-box;border:1px solid green;height:7px;width:7px;background- 
color:green;position:absolute;top:0px;left:'+randomDrop+'px;transition:transform 
10s';
rainDrop.setAttribute('id','drop'+a);
yourTankOverThere 
=document.querySelector("#drop"+a);rainDropArray.push(yourTankOverThere);


 hmm();  


 },100);    
 function hmm() 
 {rainDropArray[a].style.transform="matrix3d(1,0,0,0,0,1,0,0,0,0,1,0,0,1000,0,1)";a++}

createReactionCollector is not a function error

Error:

        const collector = message.createReactionCollector({ filter, time: 15000 });
                                  ^

TypeError: message.createReactionCollector is not a function

Code:


module.exports = {
    name: 'rules',
    description: 'Server Rules',
    permission: "ADMINISTRATOR",
    /**
     * 
     * @param {MessageReaction} message 
     */
    execute(message) {
        const rulemebed = new MessageEmbed()
        .setColor('#ffc7fe')
        .setTitle('Server Rules')
        .setDescription('Please click the check mark ✅ to verfiy that you read the rules and gain access to other channels')
        .setFooter('Abusing loop holes will result in fair punishment ')
        .addFields(
            {name: '#1', value:'...',},
        );
        

        message.channel.send({ embeds: [rulemebed] }).then((sentMessage) => {
            sentMessage.react("✅");
        });
        const filter = (reaction, user) => {
            return reaction.emoji.name === '✅' && user.id === message.author.id;
        };
        
        const collector = message.createReactionCollector({ filter, time: 15000 });
        
        collector.on('collect', async(reaction, user) => {
            const role = await message.guild.roles.fetch("916861450281156678");
            
            message.guild.members.fetch(user.id).then(member => {
                member.roles.add(role);
                member.roles.remove("916929706182459392");
            });
        });
    }
}

The code works just fine until I added the reaction collector starting at line 25 The goal is to make it when someone clicks the emoji “✅” they will be givin a role. I’m using discord.js v13 and node.js v16.13.0

Implement the form on JS + AJAX

I can’t solve the problem. I need to create a form, when I click on the buttons from the file on the server reads the name and surname and displays them in the HTML page (data will be taken from the input). The second form allows you to edit information about you and save it.

let form = document.forms.user

form.submit.addEventListener("click", sendRequest)

function sendRequest(e) {
    e.preventDefault() 
    let formData = new FormData(form) 
    let request = new XMLHttpRequest() 

    request.open()
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
             document.getElementById("output").INNERHTML = request.responsText
        }
    }

    request.send(formData)
}

I do not know how to implement all the above functionality. Help me please 🙂

How to import Firebase v9 Auth Error object (JS SDK)

Here’s where I need it:

      try {
        await updatePassword(user, password);
      } catch (e) {
        if (e instanceof AuthError) {
          setErrorMessage(e.message);
        }
      }

The reason it’s failing is because AuthError is just an interface exported from the ‘firebase/auth’ module not an actual Error subclass.

onsubmit is still submitting the form even if it returns false?

I have a form in HTML page. It includes:

<form action="result.html" method="get" onsubmit="return ValidationEvent()">

So even the ValidationEvent() returns false I can render the result.html. Below is the definition of the function:

// Below Function Executes On Form Submit

function validation() {

// Storing Field Values In Variables
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var contact = document.getElementById("contact").value;
// Regular Expression For Email
var emailReg = /^([w-.]+@([w-]+.)+[w-]{2,4})?$/;

// Conditions
if (name != '' && email != '' && contact != '') {
    if (emailReg.test(email)==true) {
        //  if (email.match(emailReg)) 
        if (document.getElementById("male").checked || document.getElementById("female").checked) {
            if (contact.length == 10) {
                alert("All type of validation has done on OnSubmit event.");
                console.log("All type of validation has done on OnSubmit event.")
                return true;
            } 
            else {
                alert("The Contact No. must be at least 10 digit long!");
                console.log("The Contact No. must be at least 10 digit long!");
                return false;
            }
        } 
        else {
            alert("You must select gender.....!");
            return false;
        }
    } 
    else {
        alert("Invalid Email Address...!!!");
        return false;
    }
} 
else {
    alert("All fields are required.....!");
    return false;
}

}

How can prevent the form to be submitted.

How do I tell what file this error is coming from?

I’m somewhat new to next.js and I’m getting this error. I’ve looked at every <a> tag I have in all my files and they all have a corresponding closing </a> tag. Am I not understanding this error properly? The only other thing I can think of is they want all my <a> tags to be wrapped inside of a <div> but I don’t know why that would be required.

Error:
Warning: Expected server HTML to contain a matching <a> in <div>.
react-dom.development.js?ac89:67

Also where is this error being thrown from because they only reference they give is to a react-dom file that I think gets generated when next converts my code to something the browser can read (not 100% sure that’s what the file is though)

screenshot of error inside chrome dev tools console

How can I implement touch control to my ping pong game?

I want to add touch controls when the game is played on touch screen devices , Ideally, the user paddle would move every time I touch the screen. Here is the code I have inputted for my key presses.

window.addEventListener(‘keydown’, keyDownHandler);
window.addEventListener(‘keyup’, keyUpHandler);

function keyDownHandler(event) {
  switch (event.keyCode) {
    case 38:
        upArrowKey = true;
        break;
    case 40:
        downArrowKey = true;
        break;
}
}

function keyUpHandler(event) {
  switch (event.keyCode) {
    case 38:
        upArrowKey = false;
        break;
    case 40:
        downArrowKey = false;
        break;
}
}

And this is the code that I inputted to move the ball if user presses key.

let userSpeed = 9;
if (upArrowKey && user.y > 0) {
 user.y -= userSpeed;
}else if (downArrowKey && (user.y < canvas.height - user.height)) {
 user.y += userSpeed;
}

How can I implement touch controls in the same way?

conditional types using generics in react component

Note: I have a working solution for this problem, but I am hoping somebody may be able to show me a more efficient and compact way to implement it.

Problem:

I have a react component like so:

function Component({ idIdentifier = "id", nameIdentifier = "name", persons }) { // render

the idea is that the persons prop should be an array of object(s) that match the identifiers specified in the idIdentifier and nameIdentifier props, for example using default prop values it should look like:

persons = [ { id: "1", name: "Joe" } ]

I want to make this component more powerful by adding type specification using TypeScript. I need the specification to be sophisticated enough so it can flag errors when the following occurs:

when using Component type of persons prop being passed in does not match specification when:

  • idIdentifier and nameIdentifier props not passed, default values used
  • Custom value for idIdentifier prop passed and
    nameIdentifier prop not passed, default value used for latter
  • Custom value for nameIdentifier prop passed and
    idIdentifier prop not passed, default value used for latter
  • Custom value for both nameIdentifier and
    idIdentifier props passed

Below is my solution:

const ID = 'id'
const NAME = 'name'

type Id = typeof ID
type Name = typeof NAME

type Persons<T1 extends string, T2 extends string> = { [key in (T1 | T2)]: string }[]

type VariableProps<T1, T2> = {
  idIdentifier?: T1
  nameIdentifier?: T2
}

type DefaultProps = {
  persons: Persons<Id, Name>
} & VariableProps<Id, Name>

type PropsWithName<T extends string> = {
  idIdentifier?: T
  nameIdentifier: Id
  persons: Persons<Id, T>
}

type PropsWithId<T extends string> = {
  idIdentifier: T
  nameIdentifier?: Name
  persons: Persons<T, Name>
}

type PropsWithIdAndName<T1 extends string, T2 extends string> = {
  persons: Persons<T1, T2>
} & Required<VariableProps<T1, T2>>

type AllProps<T1 extends string, T2 extends string> = (DefaultProps | PropsWithName<T1> | PropsWithId<T2> | PropsWithIdAndName<T1, T2>)

function Component<T1 extends string, T2 extends string>({ idIdentifier = ID, nameIdentifier = NAME, persons }: AllProps<T1, T2>) { // render

My solution does work and it will give me the warnings I need under all scenarios when there is a mismatch, but I wondered if my code could be more compact, the real world Component has more moving parts and this approach has doubled the length of the file.

Any feedback greatly appreciated, thanks.

How to update values inside an object using DOM/HTML related functions, such as onclick or addEventListener (Vanilla Javascript)

There is something about calling a function using DOM elements, such as button (onclick, addEventListener), and calling function by updating the Browser.

I am trying to change values of a key inside an object. When I do that using click on a button in HTML, the change does not sit permanently in the object – it is only relevant to that function (onclick, such as onlick or addEventListener).

But I want to be able to change the value on click of a button in HTML, so that I can use it in other functions.

How can I solve this issue?

javascript variable in mysql datenbank speichern

ich habe ein Spiel mit Javascript erstellt dort habe ich eine variable namens usersGeld. Darin ist eine Zahl gespeichert (das Geld). Desweiteren habe ich mit php und mysql ein login system gemacht jetzt möchte ich das die Variable usersGeld für jeden angemeldeten user gespeichert wird und diese verwendet wird wen er sich einlogt. Wie ist das möglich?

Weitere infos:

Der user wird in einer Tabelle gespeichert mit usersID, Name, Pwd, und usersGeld sollte noch gespeichert werden.

Danke im voraus

Jonathan

Recursive searching returns undefined

I was just practicing some native Javascript and came across this problem. I’m building a comments widget and trying to implement a ‘reply’ button. For this I have to iterate through some n number of nested comments to find the correct one and push the reply to it’s ‘responses’ attribute. This is my code so far:

 const recursiveSearch = (object, target) => {
    if(object.id === target) return object;

    let result;
    if(object.responses.length > 0) {
     object.responses.forEach(response => {
          if(response.id === target) {
              result = response;
              console.log('match found')
              console.log(response)
              return response
          } 
          
          else if(response.responses.length > 0) recursiveSearch(response, target) 
      })   
    };

    console.log('result Is')
    console.log(result)

    return result

}

The logs show the expected behavior just fine but when looking at the end return statement is undefined. Any way to get around this?

JS/HTML/CSS Image carousel not loading correctly

I am trying to include a carousel to my website, but there’s a bug where the carousel doesn’t load properly. It flashes with the image(s) but then it disappears. You can see the video below of this error.

Chrome console shows:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')
    at showSlides (index.html:540)
    at index.html:518

You can see an example here of the problem: Video example of problem

JS is as follows:

var slidePosition = 1;
SlideShow(slidePosition);
 
// forward/Back controls
function plusSlides(n) {
  SlideShow(slidePosition += n);
}
 
//  images controls
function currentSlide(n) {
  SlideShow(slidePosition = n);
}
 
function SlideShow(n) {
  var i;
  var slides = document.getElementsByClassName("Containers");
  var circles = document.getElementsByClassName("dots");
  if (n > slides.length) {slidePosition = 1}
  if (n < 1) {slidePosition = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < circles.length; i++) {
      circles[i].className = circles[i].className.replace(" enable", "");
  }
  slides[slidePosition-1].style.display = "block";
  circles[slidePosition-1].className += " enable";
}

CSS: Link to CSS code

HTML: Link to HTML code