Rock Paper Scissor Game…showing only computer as winner for every condition. what mistake i am making

I am trying to build rock paper scissor game. In this for every condition it is showing computer as winner and only the computer score is increasing. In playRound function the conditions are correct i am not able to rectify the problem here. Plz help in finding my mistake.

const choices = ["rock", "paper", "scissor"];
let computerScore = 0;
let playerScore = 0;
var computer;

function computerChoice() {
    const computerId = document.getElementById('computerid');
    computer = choices[Math.floor(Math.random() * choices.length)];
    computerId.innerHTML = computer;
    console.log(computer);
    return computer;
}

function playRound(computerSel, playerSel) {
    if (playerSel === computerSel) {
        return "It's a Tie";
    } else if (
        (computerSel === "rock" && playerSel === "paper") ||
        (computerSel === "paper" && playerSel === "rock") ||
        (computerSel === "scissor" && playerSel === "rock")
    ) {
        return "Player";
    } else {
        return "Computer";
    }
}
var playerSelection;
var computerSelection;
function playGame() {
    const buttons = document.querySelectorAll('button');
    buttons.forEach(btn => {
        btn.addEventListener('click', (e) => {
             playerSelection = e.target.textContent;
             console.log(playerSelection);
            const playerId = document.getElementById('playerid');
            playerId.innerHTML = playerSelection;
             computerSelection = computerChoice();
            const result = playRound(computerSelection, playerSelection);
            console.log(result);
            updateScore(result);
            
        });
    });
}

function updateScore(result) {
    const playerscore = document.getElementById('playerscore');
    const computerscore = document.getElementById('computerscore');
    if (result === "Player") {
        playerScore++;
    } else if (result === "Computer") {
        computerScore++;
    }
    playerscore.innerText = playerScore;
    computerscore.innerText = computerScore;
    if (playerScore === 5 || computerScore === 5) {
        endGame();
    }
}

function endGame() {
    const winner = (playerScore > computerScore) ? "Player" : "Computer";
    console.log(`The winner is ${winner}`);
}

playGame();

Can I use async call with useState(functionName)

Learning react so please bear with…

Below code works for me and allows me to set the valueOne as OneOneOne

function LoadPage()
{
const [valueOne, setvalueOne] = useState(GetValueOne)  

function GetValueOne()
{
   return 'OneOneOne';
}
}

The issue I am having is I need to make a call to the server to return the actual value of valueOne on page load… So I have changed to the following:

async function GetValueOne()
{
  let oneResult;

  await axios.get(`${getBaseUrl()}/One/GetValueOfOne`)
  .then(res => {
    oneResult= res.data;
  });

 return oneResult;
}

This is now not working as I have changed the function to async…Can I update the useState to match this?

If not is there another way to do this please?

Using jQuery find() then get attributes of the element

Here’s a simplified XML file:

const mpd = `<AdaptationSet id="1" lang="eng" mimeType="audio/mp4">
    <Representation codecs="mp4a.40.2" id="5" mimeType="audio/mp4"></Representation>
    <Representation codecs="mp4a.40.2" id="6" mimeType="audio/mp4"></Representation>
    <Representation codecs="mp4a.40.2" id="7" mimeType="audio/mp4"></Representation>
</AdaptationSet>
<AdaptationSet id="1" lang="eng" mimeType="audio/mp4">
    <Representation codecs="ec-3" id="8" mimeType="audio/mp4"></Representation>
</AdaptationSet>`

I want to get the codecs attribute of the Representation element of each AdaptationSet element.

let mpdXML = $.parseXML(mpd);
let audios = $mpdXML.find("AdaptationSet[mimeType|='audio/mp4']");
$.each(audios, (id, audio) => {
    // let codecs = $(audio).find('Representation')[0].attr('codecs');
    let codecs = $(audio).find('Representation').attr('codecs');
})

The code is work perfectly. But I think this is not the accurate solution cause Representation element may be more than one. So I add a line of code(now been commented) and it’s not gonna work. Can somebody tell me why? Cause I have seen similar example from jQuery document doing this way:

var item1 = $( "li.item-1" )[ 0 ];
$( "li.item-ii" ).find( item1 ).css( "background-color", "red" );

Thanks!

POST nested JSON object in REST api using Express.js and MongoDB

Problem I’m facing is to POST api using express.js and MongoDB,I getting in complete data save in my db, its missing behind some data of the designed schema not posting entire schema data while posting it using postman.

ThemeType:{
ThemeSelect:"",
},
CustomizerTitle: {
          bgColor: "#ffff",
          ftColor: "#ffff",
          font: "",
          fontSize: "",
          fontSizeMobile: "",
          ftColorMobile: "#2D2D2D",
          dividerColor: "#2D2D2D",
          dividerThickness: "",
        },
        LayersPanel: {
          LayerPanelPos: "",
          LaPnbgColor: "#ffff",
          LaPnbrdColor: "#ffff",
          borderThickness: "",
          errorClr: "#ffff",
        },
        LayersList: {
          LayerFtClr: "#ffff",
          LayerFntSize: "",
          LayerFntFmly: "",
          LayerDscFntClr: "#ffff",
          LayerDscFntSize: "",
          LayerDscFntFmly: "",
          LayerDivClr: "#ffff",
          LayerDivThick: "",
        },
        LayersSettings: {
          LayerSetBrdClr: "#ffff",
          LayerSetSelBrdClr: "#ffff",
          LayerSetBrdThick: "",
          LayerSetSelBrdThick: "",
          LayerSetFtClr: "#ffff",
          LayerSetFtSize: "",
          LayerSetFtFmly: "",
          LayerSetPopUpBkgClr: "#ffff",
          LayerSetPopUpBkgRound: "",
          LayerSetDescFtClr: "#ffff",
          LayerSetDescFtSize: "",
          LayerSetDescFtFmly: "",
        },
        ThumbnailButtonList: {
          ThumbnailRounding: "",
          ThumbnailColoumn: "",
          ThumbnailWidth: "",
          ThumbnailHeight: "",
          ThumbnailVerticalMargin: "",
          ThumbnailRoundMob: "",
          ThumbnailWidthMob: "",
          ThumbnailHeightMob:"",
          ThumbnailMargintMob:""
        },
        InputTextDropDown: {
          InputTxtBgClr: "#ffff",
          InputTxtHeight: "",
          InputTxtRoundings: "",
          InputTxtBrdClr: "#ffff",
          InputTxtFontFmly: "",
          InputTextFontClr: "#ffff",
          InputTextFontSize: "",
          InputTextDrpDownMenuBgClr:"#ffff",
          InputTextDrpDownHovOpClr:"#ffff",
          InputTextDrpDownSelcOpClr:"#ffff",
          InputTextDrpDownMenuFtClr:"#ffff"
        },
        FileUpload: {
          FileUploadBgClr: "#ffff",
          FileUploadBrdClr: "#ffff",
          FileUploadRound: "",
          FileUploadFtClr: "#ffff",
          FileUploadLinkClr: "#ffff",
          FileUploadFontSize: "",
          FileUploadImgRound: "",
          FileUploadRemoveIptBgClr:"#ffff",
          FileUploadRemoveIptHovBgClr:"#ffff",
          FileUploadRemoveIptIconBgClr:"#ffff"
        },
        PrintReady: {
          PrintReadyEditionClr: "#ffff",
          PrintReadyEditionIcClr: "#ffff",
          PrintReadyEditionDPIIndTxtClr: "#ffff",
          LowQualityTextClr: "#ffff",
          LowQualityMsgBkgClr: "#ffff",
          LowQualityMsgTextClr:"#ffff",
          HighQualClr:"#ffff"
        },
        Customizer: {
          LoadingIconClr: "#ffff",
          BkgClr: "#ffff",
        },
        StepTitle: {
          BkgColor: "#ffff",
          SwitchStepsArrow: "#ffff",
        },
        SummaryTitle: {
          FontFamily: "",
          FontColor: "#ffff",
          FontSize:"",
        },
        AddToCart: {
          BorderClr: "#ffff",
          BorderThickness: "",
          Rounding:"",
          FontFamily:"",
          FontColor:"#ffff",
          BackgroundClr:"#ffff",
          HoverBkgColor:"#ffff",
          FontSize:"",
        },
        ConfirmBtn: {
          FontClr: "#ffff",
          BackgroundClr:"#ffff",
        },
        Price: {
          PricePosition: "",
          PriceFont: "",
          FontSize: "",
          FontSizeMb: "",
          FontColour: "#ffff",
          ShowExtraPrice: "",
          ExtraPriceFontClr: "#ffff",
          ExtraPriceBrClr: "#ffff",
          ExtraPriceBgClr: "#ffff",
        },
        SwitchViewArrows: {
          Color: "#ffff",
        },
        SwitchViewDots: {
          colour: "#ffff",
          SelectColour: "#ffff",
        },
        zoom: {
          ZoomClr: "#ffff",
        },
        ShareButton: {
          DisplayShrBtn: "",
          IconOrTxtButton: "",
          ShrBtnClr: "#ffff",
          TextBtnRnd: "",
          TextBtnLnth: "",
        },
        DescriptionMobile: {
          DescMbClr: "#ffff",
          DescMbBkgClr: "#ffff",
          DescMbFontFmly: "",
          DescMbFontSize: "",
        },
        OutOfStock: {
          badgeIconClr: "#ffff",
          badgeBkgClr: "#ffff",
          badgeBrWidth: "",
          badgeBrClr: "#ffff",
          BannerTextClr: "#ffff",
          BannerBgClr: "#ffff",
        },
      } 

This is my object JSON, schema which I’m trying to post but getting missed many data while posting, this what saving in POST request data obj:

FileUpload
Object

PrintReady
Object

Customizer
Object

StepTitle
Object

SummaryTitle
Object

AddToCart
Object

ConfirmBtn
Object

Price
Object

SwitchViewArrows
Object

SwitchViewDots
Object

zoom
Object

ShareButton
Object

DescriptionMobile
Object

OutOfStock
Object

I’m trying in this way :

const postCustomizerData = async (req, res) => {
    try {
        // const newData = req.body; // Assuming the data is sent in the request body
        // const data = await Customizer.create(newData);
        // res.status(201).json(data);
        const newData = req.body;
        console.log("NewData:", newData)
        const data = new Customizer(newData);
        await data.save();
        res.status(201).json({ success: true, data: data })
    } catch (error) {
        console.log("Error:", error)
        res.status(500).json({ error: 'Internal Server Error' });
    }
};

AlpineJS $persist – save option once per page

I have a select dropdown built with AlpineJS and the chosen value is currently saved to sessionStorage once an option is chosen. However, the values for these options are different based on each page these options are available.

The problem is, if a user chooses an option on one page, then changes their mind and accesses a different page with different options, the first chosen option saved in sessionStorage will populate on any other page when the options are different.

Here is the code:

x-data="{ charter: $persist('').using(sessionStorage).as('_x_charterlength') }"
<div
    x-data="{ open: false }"
    @click.away="open = false"
    class="relative flex-1"
    >
        <!-- Button -->

        <button @click="open = !open"
            class="flex items-center justify-between flex-1 w-full gap-2 px-4 py-2 text-left bg-white border border-gray-400 rounded-lg"
            :class="[charter === '' ? 'border-2 border-orange-500' : '']"

        >
            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-geo-alt-fill" viewBox="0 0 16 16">
                <path d="M8 16s6-5.686 6-10A6 6 0 0 0 2 6c0 4.314 6 10 6 10m0-7a3 3 0 1 1 0-6 3 3 0 0 1 0 6"/>
            </svg>

            <span class="w-full ml-2 overflow-hidden text-sm text-gray-600 whitespace-nowrap"
                x-text="charter === '' ? 'Add charter length' : charter"
            ></span>
        </button>
        <div x-show="open"
            class="absolute left-0 z-50 w-full p-4 mt-2 text-sm bg-white rounded-md shadow-md"
            x-cloak
        >
            <ul class="overflow-auto [&>li]:text-gray-500 [&>li]:px-4 [&>li]:py-2 hover:[&>li]:bg-gray-100 [&>li]:cursor-pointer space-y-2"
            >
            {{ pricing }}
            {{ if half_day }}<li @click="charter = $el.textContent; open = false;" class=" whitespace-nowrap"><span>1/2 Day: </span><span class="font-bold">${{ half_day }}.00 </li>{{ /if }}
                {{ if three_quarter_day }}<li @click="charter = $el.textContent; open = false;" class="whitespace-nowrap"><span>3/4 Day: </span><span class="font-bold">${{ three_quarter_day }}.00 </li>{{ /if }}
                    {{ if full_day }} <li @click="charter = $el.textContent; open = false;" class="whitespace-nowrap"><span>Full Day: </span><span class="font-bold">${{ full_day }}.00 </li>{{ /if }}
            </ul>
            {{ /pricing }}
        </div>
        <div x-text="[charter == '' ? 'Choose charter length' : '']" class="mt-1 text-xs font-bold text-orange-500"></div>
    </div>

My question is:
How can save the chosen option for a given page in sessionStorage but have it be removed if they visit another page with the same dropdown but different options?

JavaScript: If String Is Not A or B Then

How do I achieve this with a single if ? In other words, if(fruit != "apple" || fruit != "orange"){ is not producing the expected result?

fruits.forEach(function(fruit){
  if(fruit != "apple"){ // < ----I want to use a compound OR, or compare multiple strings.
    if(fruit != "orange"){ // <---------I want this nested if gone.
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});

const fruits = ["apple","orange","banana","cherry"];

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    console.log(fruit + " is not apple");
  }
});

fruits.forEach(function(fruit){ //<------- this is what I'm having problems with
  if(fruit != "apple" || fruit != "orange"){
    console.log(fruit + " is not apple or orange [one]");
  }
});

fruits.forEach(function(fruit){
  if(fruit != "apple"){
    if(fruit != "orange"){
      console.log(fruit + " is not apple or orange [two]");
    }
  }
});

How to pass in a dynamic parameter to a function inside of a addEventListener scroll as it seems to get memoized?

So I have states as this:

const [pointer, setPointer] = useState("");

And I update this state whenever I fetch data from an API as such:

const fetchData = (fileType) => {
  if (pointer === null) return;
  API.call(pointer).then((res) => setPointer(res));  
};

const triggerRefetch = () => {
  if (!hasMore) return;
  const element = loadingRef?.current?.getBoundingClientRect();
  if (element?.top < window.innerHeight && element.bottom >= 0) {
    fetchData(fileType);
  }
};

useEffect(() => {
  triggerRefetch();
  const el = document.getElementById("room-detail-container");
  el?.addEventListener("scroll", triggerRefetch);

  return () => el?.removeEventListener("scroll", triggerRefetch);
}, []);

So my idea is to implement some sort of an infinite scrolling feature, where if the Loader component is visible on the screen, it will trigger a refetch to the API. That’s why I use the addEventListener("scroll", ...). And I’m using this pointer to know exactly what’s the next data I want to fetch. However, whenever this triggerRefetch, it seems that the fetchData function somewhat memoize the pointer state, so even though the pointer state has been updated through setPointer(res), if I console.log(pointer) inside of the function, it returns me an empty string. Is there a way I can get around this?

how to decrypt after adding random letter after every two letters javascript

const alphabet = "abcdefghijklmnopqrstuvwxyz";

function encrypt (message, shiftValue)
{   
    let encryptedMessage = ''; // somewhere for the message to be stored
    for (i = 0; i < message.length; i++){
      let char = message[i].toLowerCase(); // each character made lowercase

      if (alphabet.includes(char)) { // if alphabet includes the character
        const idx = alphabet.indexOf(char);// find its index
        const newIdx = (idx + shiftValue) % alphabet.length;// then add the shift value to it     while going through the alphabet
        encryptedMessage += alphabet[newIdx] // add/store it as the message

        if ((i + 1) % 2 === 0) {
          const randomIndex = Math.floor(Math.random() * 26);
           encryptedMessage += alphabet[randomIndex];// every two character a random letter is     added
        }
      } else {
        encryptedMessage += char;
      }
    }

  return encryptedMessage;
}

function decrypt (encryptedMessage, shiftValue)
{
  let decryptedMessage = '';

  for (i = 0; i < encryptedMessage.length; i++){
    const char = encryptedMessage[i].toLowerCase();

    if (alphabet.includes(char)) {
        const idx = alphabet.indexOf(char);
        const newIdx = (idx - shiftValue  + alphabet.length) % alphabet.length;
        decryptedMessage += alphabet[newIdx]
    }else {
    decryptedMessage += char;

    } 
  }
  // Your decryption code here
  return decryptedMessage;
}

I’m brand new to coding and have used many an online resource to scramble this together. I even consulted chatgpt at one point and feel so dumb for that. I mainly would like some feedback on how the code is and to help me solve a problem that I cant quite find online or seem to figure out myself. below the requirements will be posted

  1. Implementing the Encryption Algorithm of Caesar’s Cipher
    • Step 1: Take a plaintext message and a shift value and return an encrypted string. If the message includes a character out of the alphabet, pass it as is to the encrypted string.
    • Step 2: After every two letters, insert a random letter from the alphabet.
  2. Implementing the Decryption Algorithms of Caesar’s Cipher
    • Take in the encrypted message and a shift value and return the original plaintext message.
    • Accurately reverse the encryption process to retrieve the original message.
  3. Decrypting the Secret Message
    • Iueuan jrxuq cjythdykwxaj mixkqtaeml ebv wHenckvbkei rqdmt fHukckvi.r Jbxuihus, tmxayiwfuxh sjxau amenhtv ‘zQkhhuubyjkit’ yjew jhxux mxydatij. zJxmu hvymhihj ajel kldlsuyjb dyju yid uekdh qIbkqsxa xsxqqdvduzb wuqzhdoi qjxwu waueo xjem jfxuy dpuntj dgkvuiwj.
    • Decrypt the above secret message using 42 as the shift value and complete the quest.

My main question in all of this is how do I reverse the fact that a random letter is added after every two letters to properly decrypt not only the messages I put through it but the required message. I get most of the message i put through back. The required decryption I only ever get back undefined.

This is my first post on here, I hope I’ve formatted and asked this properly thank you to any and all who help me brainstorm this!

I’ve not tried anything as of yet I’m still very new and feel like I cheated even scraping together what I have above by looking up most of it.

Why does scrollIntoView not work in Chrome on iOS?

When a filter link nav .fixed a is clicked, the page is scrolled to the top of the content section #category-content via scrollIntoView.

Results in the following browsers:

macOS

Firefox ✅

Safari ✅

Chrome ✅

iOS

Firefox ✅

Safari ✅

Chrome ❌

In iOS Chrome nothing happens. The filter links work, but no page scroll. There is also no relevant CSS; #category-content is a direct child of body, with no CSS on it.

Browser versions have been updated. Caches cleared. Phone restarted. No console errors.

Is there something here that is causing it, or perhaps something about Chrome for iOS to consider?

HTML

<nav id="filters">
  <ul class=“fixed”>
    <li><a href="#" data-filter="all" class="active">All</a></li>
    <li><a href="#" data-filter="text-inputs">Text &amp; Inputs</a></li>
    <li><a href="#" data-filter="controls">Controls</a></li>
    <li><a href="#" data-filter="scrolly-stuff">Scrolly Stuff</a></li>
    <li><a href="#" data-filter="other">Other</a></li>
  </ul>
</nav>


<div id="category-content">
   <!— Content —>
</div>

JS

document.querySelectorAll('nav .fixed a').forEach(navLink => {
  navLink.addEventListener('click', (event) => {
    // Get the element
    const categoryContent = document.getElementById('category-content');
      // Scroll to the element
      categoryContent.scrollIntoView();
  });
});

‘…’ only refers to a type, but is being used as a value – Typescript / Javascript – import NodeJS Lib [duplicate]

I have a simple NodeJS library that exports a few constants. In that lib, we have the following setup :

the-lib/index.js

  const SOME_EXAMPLE = [
    {
       'AAA': ['BBB']
     ...
    }  
  ]

  module.exports = {
    SomeExample: SOME_EXAMPLE
  }

the-lib/index.d.ts

  export type SomeExample = Record<string, string[]>
  

I also have another repo, which is a NodeJS project, in which I want to use this library. As such :

service/src/index.js

 import {SomeExample} from './the-lib
 console.log(SomeExample)

service/ts-config.json

... // This is just an extract to give an idea
"compilerOptions": {
  "target": "es2022",
  "module": "CommonJS",
  "esModuleInterop": true,
  "allowSyntheticDefaultImports": true,
  "skipLibCheck": true,
...

When starting the service, typescript throws with 'SomeExample' only refers to a type, but is being used as a value.

What am I doing wrong ?

I do see there’s a similar question here : ‘string’ only refers to a type, but is being used as a value here However I don’t think the problem is the same. I suspect what we are dealing with here is an import/export issue.

File Upload – can multiple file attempts be added instead of replaced?

I have an input field:
<input type="file" id="images" name="images[]" value="" class="test" multiple="">

This is a file upload with multiple file upload ability.

Is it possible to make is so the input fields adds the files when user uploads files in multiple attempts?

Example:

CURRENT FLOW:

  1. User uploads 3 images

(User remembers he has more images)

  1. User Uploads 2 more images

Result: 2 images added to input field.

WHAT I WANT:

  1. User uploads 3 images

(User remembers he has more images)

  1. User Uploads 2 more images

Result: 5 images added to input field.

Is this possible or this will require rewriting how the input field works?

PS: currently I’m using a WordPress plugin to manage the upload field, so I cant do too many modifications on the backend. I was wondering if front-end(JS) can be used to pool up the items?

I tried writing a bunch of JS to manage this field, but every time the popup for the files shows up and you add the items, it just overwrites the previously uploaded files.

Php nav bar menu

I need some help with php, I have a code that when you open the website in a mobile, the nav bar menu disappears,
Can anyone help me with this please.

Let me know how I can get in touch, thank you.

I tried changing the js, the html, and css but still I am not getting any results. 🙁

Get data from json and use parameter when calling them

is it possible to get a test data from json but using parameter in calling the data

const dataCredentials = JSON.parse(JSON.stringify(require('../fixtures/credentials.json')));
const env = process.env.ENV

It is getting the proper data using this

const usrName = dataCredentials.dev.username

But I want to make the environment dynamic that is why I converted the code like below:

const usrName = `${dataCredentials}.${env}.username`
console.log("USER CREDENTIALS>>>>> " + usrName)

When I run the code, I am getting below

USER CREDENTIALS>>>>> [object Object].dev.portal_ff_username