Diner Menu with Javascript [duplicate]

Im learning JS and trying to do a Diner Menu using “prompt” and “alert”, but I get stuck on having the values and the total aswell.. please help. here is my code :

const  menu = {
 "hotdog": 1.00,
  "hamburger" : 3.00,
  "lasagna" : 4.00,
  "chilli_cheese_fries" : 3.00,
  "soda" : 3.00,
  "popcorn" : 2.00,
  "salad" : 6.00
}

console.log(menu);
const menu_1 = Object.keys(menu)

var name = prompt("Hello what's your name?");
var saludo = prompt("Hello " + this.name + "!"  + " What would you like to order?") // 'hotdog' = 1
var side = ("Please select a side") // hamburger = 3
const total = (this.menu_1[this.saludo] + this.menu_1[this.side])
// var saludo_1 = "salad"
// var please = ("please enter your name")

alert(this.total)

const bill = prompt(`Your bill is ${total}`)


console.log(total);

I’m having trouble loading an .svg image in react using styled components. Can anyone tell me why its not loading?

here is the code. I tried using .default but it still wont load. I also have it imported correctly in my index.js. No errors show up and when I inspect the page there is an image. any suggestions would be greatly appreciated.

export const homeObjOne = {
    id: 'about',
    lightBg: false,
    lightText: true,
    lighTextDesc: true,
    topLine: 'Something Here',
    headline: 'I will write something here later',
    description: 'I will write something here later',
    ButtonLabel: 'Get started',
    imgStart: false,
    img: require('../../images/svg01.svg'), /* .default does not work either */
    

How pass variable in a JSON in JavaScript? [duplicate]

Why _uuid and not the value of _uuid is in the JSON?

let _uuid = uuid()

const json = {
                name: 'Opció neve pl. pénteki érkezés',
                invoiceItems: {
                    _uuid: {
                        name: 'Számlatétel megnevezése',
                        vatKey: 'AAM',
                    },
                },
            }

Is it any better solution than do a string extrapolation and then a JSON parse?

Is there a way to spoof `window.devicePixelRatio` in webview?

I am doing some testing on whether or not it is possible to spoof

// returns the ratio of the resolution in physical pixels to the resolution in CSS pixels
window.devicePixelRatio

// when this javascript code is run on a Pixel 4
window.devicePixelRatio == 2.75

// when this javascript code is run on a iPhone 8
window.devicePixelRatio == 2.00

Is it possible to configure WebView.getSettings() to change this value programmatically?

Only one part of my reset function will run

When rendering this code, there is a reset button that should reset the score for a blue player and a red player, but only one of the players resets and the other doesnt even though the function includes both. The js object is called reset.

JS Script

blueScore = document.querySelector("#score_blue");
redScore = document.querySelector("#score_red");
blueIncr = document.querySelector(".blue");
redIncr = document.querySelector(".red");
reset = document.querySelector(".reset");
var blueInt = 0;
var redInt = 0;

blueIncr.addEventListener('click', function(){
    blueInt++;
    blueScore.innerText = blueInt;
});
redIncr.addEventListener('click', function(){
    redInt++;
    redScore.innerText = redInt;
});
reset.addEventListener('click', function(){
    redInt == 0;
    blueInt = 0;
    redScore.innerText = redInt;
    blueScore.innerText = blueInt;
});

HTML markup

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <link rel="score_keeper_style" href="style.css">-
  </head>
  <body>
    <div>
        <h2>
            <span id="score_blue">0</span> to <span id="score_red">0</span>
            <div>
                <input list="playto" name="play to:"/>
                <datalist id="playto">
                    <option value="f1">
                    <option value="2">
                    <option value="3">
                    <option value="4">
                    <option value="5">
                </datalist>
            </div>
        </h2>
    </div>
    <div>
        <button class="blue">Team Blue</button>
        <button class="red">Team Red</button>
        <button class="reset">Reset</button>
    </div>
    <script src="score_keeper_my_version.js"></script>
  </body>
</html>

Why is this infinite loop?

Sorry if this is a newbie question I am trying to place three strings into an array size of 9 that holds them three string placed at random indexes in the array but how I am trying to do it is resulting in an infinite loop

const ticketArray = [];
const victoryMultipliers = ["x10", "x20", "x30", "x40", "x50", "x60"];

const threeOfThem = [];
let arr = []
let randStr = "";
for (let i = 0; i < 3; i++) {
    threeOfThem[i] = victoryMultipliers[Math.floor(Math.random() * victoryMultipliers.length)]
    randStr = threeOfThem[i]
    //console.log(randStr)

    arr = threeOfThem.filter(val => val === randStr)

    if (arr.length >= 2) {
        threeOfThem.pop();
        i--;
    }
    
}
const threeTicketArray = threeOfThem;
/// So above we have an array of example ["x20", "x50", "x30"]

// so below is where we have some problem


let randInt;
let tempStr = "";
for (let i = 0; i < 10; i++) { // i want to make an array.length of 9
    randInt = Math.floor( Math.random() * 3 );
    tempStr = threeTicketArray[randInt]; // to find the "x30" or whichever i stored

  ticketArray.push(tempStr); // push it into the ticketArray
  let len = ticketArray.filter(val => val === tempStr) // we filter to bring out the once for this loops iteration
  
    if ( len.length > 3 ) { // if I have 4 of example "x30"
        ticketArray.pop(); // I remove it as it was the last "x30" string added to the array
      i--; // I subtract the iteration by 1 so I can restart the this iteration of the loop 
    }
}
// the end of the loop
console.log(ticketArray);


so at random I want ticketArray to be of size 9 the ticket strings to be placed at a random index and each string appears 3 times

but I am getting infinite loop i cant understand why!

Please help as I am out of ideas atm

jquery .ajax() vs js .then() .catch()

I’ve found myself stuck again on this I have some code and to sum it up in a nutshell, there is only one product in size ‘xs’ and it can be added to the cart. If someone tries to add it to the cart again it will show an error saying “all size xs are in your cart”.

What I do not understand is that the first code block is jquery and that’s exactly what I am trying to get away from, it does work though. All I am trying to do is to convert this to vanilla js but the jquery .ajax() method seems to be working different than fetch for some reason.

The second code block does not work because it is always successful. When all size xs are added to cart in first block then it goes into the error block.

here is the working block:

$.ajax({
   type: 'POST',
   url: '/cart/add.js',
   data: data,
   dataType: 'json',
   success: (data) => {
      console.log(data);

      if(_utils.isMobile()) {
         document.dispatchEvent(new CustomEvent('render:cart'));
                
         const sizeOption = data.options_with_values.find(item => {
            return item.name == 'Size';
         });
                
         if (sizeOption) {
            const notifyMessage = 'Size ' + sizeOption.value + ' added to your bag. <a href="#refresh-cart" class="notification__link">View bag</a>';
            mobileNotification.open(notifyMessage);
            this.refreshCart(false);
         }
         else {
            this.refreshCart(true);
         }
      }
      else {
         this.refreshCart(true);
      }
   },
   error: function(error) { 
      console.error(error);
         if ($('.ProductForm__Error').length == 0) {
            $('.ProductForm__AddToCart').after('<div class="ProductForm__Error Alert Alert--error">' + error.responseJSON.description + '</div>');
         }
              
         setTimeout(() => {
             $('.ProductForm__Error').remove();
         }, 4000);
      }
 }); 

So naturally all I did was use fetch and I stuck everything in the success callback here in the .then() and the error code I put in the .catch

fetch('/cart/add.js', {
   method: 'POST',
   body: JSON.stringify(data),
   headers: {
      'Content-Type': 'application/json'
   }
}).then(res => res.json())
  .then(data => {
      console.log(data);

      if(_utils.isMobile()) {
         document.dispatchEvent(new CustomEvent('render:cart'));
         const sizeOption = data.options_with_values.find(item => {
            return item.name == 'Size';
         });
                
         if (sizeOption) {
            const notifyMessage = 'Size ' + sizeOption.value + ' added to your bag. <a href="#refresh-cart" class="notification__link">View bag</a>';
            mobileNotification.open(notifyMessage);
            this.refreshCart(false);
          }
          else {
             this.refreshCart(true);
          }
       }
       else {
         this.refreshCart(true);
       }
  }).catch(error => {
      console.error(error);
      if ($('.ProductForm__Error').length == 0) {
         $('.ProductForm__AddToCart').after('<div class="ProductForm__Error Alert Alert--error">' + error.responseJSON.description + '</div>');
      }
              
      setTimeout(() => {
         $('.ProductForm__Error').remove();
      }, 4000);
})

how can you improve this algorithm for finding the smallest positive integer not in an array


function findSmallestPositiveInteger(A) {


    // sort array from smallest to largest number
     A.sort((a, b) => a - b)
     
    // remove duplicates because they just would take memory
    const noDups =Array.from(new Set(A).keys())
    
    let smallestPositiveInteger=1
    
    let previous = noDups[0]
    if(previous <= smallestPositiveInteger && previous>0)
            smallestPositiveInteger++
    
    for(let i =1;i<noDups.length;i++){
      const v = noDups[i]
      if(previous > 0){
         const diffWithPrevious = v - previous
         // the logic for this early return is that we might not need to traverse
         // the whole array for example imagine this example 
         // [1,2,5,6,8,...n]
         // its clear that there is a gap between 5 and 2 so we can just 
         // conclude that 2+1 is the smallest postive integer not in our array 
         if(diffWithPrevious > 1) return previous +1;      
      }
      
      // check if smallest positive integer in array is not 1
      // if so return 1 
      if(previous == 0 && v > 1 ) return 1
      
      if(v <= smallestPositiveInteger && v>0)
         smallestPositiveInteger++
       previous = v
    }

    return smallestPositiveInteger
}


const arr =[-1,-2,1,3,10,9,3,2,3,3,10,2,7,99,100,10000,500,50,60,70,33]

console.log(findSmallestPositiveInteger(arr))

Javascript, replace “,” with “.” in JSON

I have as an input a JSON string with this structure:

{
 "Seq_N":66,
 "Uptime":728,
 "Hum":33,500000,
 "Temp (C)":20,129999
}

I need to replace the comma character inside the Hum and Temp fields with a dot character, but I also need to keep the comma separators of the JSON string (in order not to break the JSON sintax)

Does anyone know a clean function / regex to do this?

Thanks in advance

Smart way to aggregate API data async

I am looping through a list of objects that each have a single key-value pair, address which is type string

I want to built an object with the results of API requests for each address that tell me how often a token symbol appears. However, I think that because I’m running all of these requests in parallel, I may be over-writing the tokenKeyValue count. Is there a smarter way of doing this, that preserves the parallelization to keep things fast?

const tokenKeyValue: any = {};
let addressesCompleted = 0;
segment.users.forEach(async (user: {address: string}, i) => {
  try {
    const tokenBalances = await getBalancesForUser(
      user.address,
    );

    if (tokenBalances && tokenBalances.length > 0) {
      for (const token of tokenBalances) {
        if (tokenKeyValue[token.symbol]) {
          tokenKeyValue[token.symbol]++;
        } else {
          tokenKeyValue[token.symbol] = 1;
        }
      }
    }
  }
  catch(e) {
    console.error(e);
  }
  finally {
    addressesCompleted++;
    // Check we are done looping
    if (addressesCompleted === segment.users.length) {
      // Calculate final tokenCount
      const tokenCount = [];
      for (const token in tokenKeyValue) {
        tokenCount.push({
          symbol: token,
          value: tokenKeyValue[token],
        });
      }
    }
  }
})

Vue i18n – object with translation variables in js file

i’m working with Vue, Vue i18n and Quasar.

So, i have an js file that contains an object with id and name, which i use on q-select options. I want that when i change the language (on language drop-down), the label name from months changes too. But this happens only if i refresh the page.

Vue component:

<q-select
  v-model="monthValue"
  :options="monthOptions"
  map-options
  emit-value
  option-value="id"
  option-label="name"
  outlined
  dense
/>
import {months} from "../../components/basic/Months.js";
computed: {
monthOptions() {
      return months;
    },

Months.js

import { i18n } from "../../boot/i18n.js";

export const months = 
    [{ id: "January", name: i18n.t("MONTHS.JANUARY") },
    { id: "February", name: i18n.t("MONTHS.FEBRUARY") },
    { id: "March", name: i18n.t("MONTHS.MARCH") },
    { id: "April", name: i18n.t("MONTHS.APRIL") },
    { id: "May", name: i18n.t("MONTHS.MAY") },
    { id: "June", name: i18n.t("MONTHS.JUNE") },
    { id: "July", name: i18n.t("MONTHS.JULY") },
    { id: "August", name: i18n.t("MONTHS.AUGUST") },
    { id: "September", name: i18n.t("MONTHS.SEPTEMBER") },
    { id: "October", name: i18n.t("MONTHS.OCTOBER") },
    { id: "November", name: i18n.t("MONTHS.NOVEMBER") },
    { id: "December", name: i18n.t("MONTHS.DECEMBER") }
  ];

I’ve tried so many things, but to no avail.. Does anyone have suggestions? Thanks.

Não estou conseguindo passar essa linha de teste, porque o retorno dele esta esperando outra função [closed]

Não estou conseguindo passar essa linha de teste, porque o retorno dele esta esperando outra função.

TsFile
  findById(id: string){
    let parameters: JavaConnectorParameters = new JavaConnectorParameters();
    parameters.addParam('id', id);

    return this.javaConnector.createRequest(RestMethod.GET, this.restMapping, '/find-by-id', parameters);
  }




specFile
 it('should call the service', () => {
    service.findById('id');
    spyOn(ProgressCheckListAPI.prototype, "findById").and.callThrough();
    ProgressCheckListAPI.prototype.findById('id');
    expect(service.findById).toHaveBeenCalled();

  });

TypeError: Cannot read properties of undefined (reading ‘createRequest’)

How to Export JSON data to Excel Work Sheet?

I’m working on a web app that gets JSON data and then exports it as an Excel worksheet containing the same JSON array as an Excel Table So, How can I accomplish this?

What I have tried so far is I used This Jquery Plugin called ( excelexportjs.js ) it’s exporting an xls file and the worksheet is completely empty

main.js

async function readFile(fileName) {
  console.log({ fileName });

  return await Tesseract.recognize(fileName, 'eng', {
  
    logger: m => console.log(m)
  });

}
async function parseDataFromTextAndPropertyNames(text, propertyNames) {
  console.log({ text, propertyNames });

  return propertyNames
    .reduce((table, key) =>
      Object.assign(table, {

        [ key ]: RegExp(`${ key }\W+(\w+)`)
          .exec(text)?.[1] ?? ''

      }), {});
}
async function writeParsedTextDataAsJSON(fileName, table) {
  console.log({ table });
   JSON.stringify({ table });

  // fake it ...
  return (await new Promise(resolve =>
    setTimeout(() => {

      console.log({ fileName, json: JSON.stringify({ table }) });
      resolve({ success: true });

    }, 1500)
  ));
}

console.log('... running ...');

(async () => {
  const { data: { text } } = await readFile('sd.png');

  const data = await
    parseDataFromTextAndPropertyNames(text, ['servicepoint', 'fuckyou']);
document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
    $("#dvjson").excelexportjs({
  containerid: "dvjson", 
  datatype: 'json', 
  dataset: data, 
  columns: getColumns(data)     
  });
  const result = await writeParsedTextDataAsJSON('myjsonfile.json', data);

  console.log({ result });
})();

excelexportjs.js plugin