get only innerHTML value from an array of divs in javascript to build a calculator

I am new to JS, my plan is to build a simple calculator using 4 functions:

calculate();
getOperator();
getResults();
clearInputField();

However, I am struggling right at the beginning. I already converted my NodeList into an array. However, this array consists of Divs. I only want to get the innerHTML value of each index and pass this value to calculate. Would anyone be able to shed me some light on how could I achieve that?

let calcNumber = document.querySelectorAll("[data-number]");
let cellsArr = Array.prototype.slice.call(calcNumber);
let operatorsValue = document.querySelectorAll("[data-operator]");
let equal = document.getElementById("equal");



calcNumber.forEach((cell) => {
    cell.addEventListener("click", calculate);
});


// operatorsValue.forEach((opt) => {
//     opt.addEventListener("click", getOperator);
// });

// equal.addEventListener("click", getResults);

let value1;
let value2;
let results;

function calculate() {



}


---HTML--
<body>

    <div class='main-container'>
        <input>
        <div id="display"></div>
        <div data-firstValue class="firstValue"></div>
        <div data-secondValue class="secondValue"></div>
        <div class="calculator-container">
            <div data-number="0" class="cell">0</div>
            <div data-number="1" class="cell">1</div>
            <div data-number="2" class="cell">2</div>
            <div data-number class="cell">3</div>
            <div data-number class="cell">4</div>
            <div data-number class="cell">5</div>
            <div data-number class="cell">6</div>
            <div data-number class="cell">7</div>
            <div data-number class="cell">8</div>
            <div data-number class="cell">9</div>
            <div data-operator class="cell">+</div>
            <div data-operator class="cell">-</div>
            <div data-operator class="cell">x</div>
            <div data-operator class="cell">÷</div>
            <div id="equal" data-equals class="cell">=</div>
            <div data-delete class="cell">AC</div>
            <div data-singleDelete class="cell">←</div>
        </div>

        <script src="script1.js"></script>

</body>

</html>

Usage of useRef with debounce function

I have the following setup in a react component where I have used the debounce function from throttle-debounce package to log the input value for testing ( actually calling an API to fetch data ).

import React, { useState, useRef } from 'react';
import debounce from 'throttle-debounce/debounce';

const MyComponent = () => {
  const [localSearchQuery, setLocalSearchQuery] = useState('');
  
  const setSearchQueryInParams = debounce(2000, value => console.log(value))

  const setSearchQuery = value => {
    setLocalSearchQuery(value);
    setSearchQueryInParams(value);
  };

  return (
    <>
      <Input
        value={localSearchQuery}
        onChange={setSearchQuery}
      />;
    </>
  );
};

But, it’s not working as expected. If I type hello in the input box, I get the following output in console:

h
he
hel
hell
hello

However, if I wrap the debounce function with useRef, it works as expected

const setSearchQueryInParams = useRef(debounce(2000, value => console.log(value))).current
Input: hello
Output in console: hello

My question is, why the debounce function is not working without useRef and how useRef is functioning here to get the desired output?

Thank you for the help.

I want to make Json a tree in typescript

enter image description here

I want to create a list by integrating overlapping values into one group, such as address, but I don’t know what to do. Help me.

{
  name: 'Leanne Graham',
  username: 'Bret',
  email: '[email protected]',
  address: {
    street: 'Kulas Light',
    suite: 'Apt. 556',
    city: 'Gwenborough',
    zipcode: '92997-3874',
    geo: {
      lat: '-37.3159',
      lng: '81.1496'
    }
}

I think I can render it only if I make it like this, but what should I do?

Find Sum of each array combinations

I need to Find Sum of each array combinations & required each combination in each line.
How to get the sum of each combinations and display it in each line with innerHTML ?

var arraysToCombine = [
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
];
var getAllCombinations = function (arraysToCombine) {
    var divisors = [];
    for (var i = arraysToCombine.length - 1; i >= 0; i--) {
        divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;

    }

    function getPermutation(n, arraysToCombine) {
        var result = [],
            curArray;
        for (var i = 0; i < arraysToCombine.length; i++) {
            curArray = arraysToCombine[i];
            result.push(curArray[Math.floor(n / divisors[i]) % curArray.length]);
        }
        return result;
    }
    var numPerms = arraysToCombine[0].length;
    for (var i = 1; i < arraysToCombine.length; i++) {
        numPerms *= arraysToCombine[i].length;
    }
    var combinations = [];
    for (var i = 0; i < numPerms; i++) {
        combinations.push(getPermutation(i, arraysToCombine));
    }
    return combinations;
}
document.write(getAllCombinations(arraysToCombine));

Created the dynamic radio, but it is affect others

I have created the dynamic radio list , and it is displaying correct data based on item.

   {item.responseType === "radio" && (
                          <div className="form-control-wrap">
                            {item.options
                              .split(",")
                              .map((list, indexRadio) => (
                                <Form.Check
                                  key={indexRadio}
                                  id={item.id}
                                  label={list}
                                  name="radio"
                                  value={list}
                                  onChange={(e, indexRadio) =>
                                    handleChange(e, indexQuestion)
                                  }
                                  type="radio"
                                />
                              ))}
                          </div>
                        )}

But When I am selecting ant one option it is affecting others,

Like if I select Question No 1 ,it is working fine ie : it is selecting only one option, but when move to Question number 2 and select any option it is selecting data from question 2 but, question one options will set to initial state.(it is getting reset)

Let me know what should I do ?

How to prevent text overlapping in Two column Grid

I have a two-column, four-row layout, but the text in the left column overflows the content in the right column.
Here is the code, which shows that the problem exists even on a larger screen.

I’m currently using tailwind CSS

enter image description here

<div className="grid text-sm md:grid-cols-2">
  {/* Name */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Name</div>
    <div className="px-2 py-2">Sazzad khdaskdhsakdhakhd</div>
  </div>
  {/* username */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Username</div>
    <div className="px-2 py-2 ">username init</div>
  </div>
  {/* Gender */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Gender</div>
    <div className="px-2 py-2 ">Male</div>
  </div>
  {/* Contact no */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Contact No.</div>
    <div className="px-2 py-2 ">
      24545413565614874
    </div>
  </div>
  {/* Shipping Address */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold"> Shipping Address</div>
    <div className="px-2 py-2">sdasdascdfsgfsdfvsdvsdvsvs</div>
  </div>
  {/* Billing Address */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Billing Address</div>
    <div className="px-2 py-2 ">sdasdascdfsgfsdfvsdvsdvsvs</div>
  </div>
  {/* Email */}
  <div className="grid grid-cols-2 overflow-hidden">
    <div className="px-4 py-2 font-semibold">Email.</div>
    <div className="px-2 py-2 ">
      <a className="text-blue-800 " href={`mailto:${[email protected]}`}>
        [email protected]
      </a>
    </div>
  </div>
  {/* BirthDay */}
  <div className="grid grid-cols-2">
    <div className="px-4 py-2 font-semibold">Birthday</div>
    <div className="px-2 py-2">25/12/2005</div>
  </div>
</div>;

How to pass dynamic value to the vactor URL in openlayers in following code

please check this Example, how can i make it dynamic , how can i pass values from drop down to the url in OpenLayers

var source = new ol.source.Vector({
url: ‘https://openlayers.org/en/v3.20.1/examples/data/geojson/switzerland.geojson’,
format: new ol.format.GeoJSON()
});
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: ‘rgba(255, 255, 255, 0.6)’
}),
stroke: new ol.style.Stroke({
color: ‘#319FD3’,
width: 1
}),
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: ‘rgba(255, 255, 255, 0.6)’
}),
stroke: new ol.style.Stroke({
color: ‘#319FD3’,
width: 1
})
})
});
var vectorLayer = new ol.layer.Vector({
source: source,
style: style
});
var view = new ol.View({
center: [0, 0],
zoom: 1
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
vectorLayer
],
target: ‘map’,
controls: ol.control.defaults({
attributionOptions: /** @type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: view
});

  var zoomtoswitzerlandbest = document.getElementById('zoomtoswitzerlandbest');
  zoomtoswitzerlandbest.addEventListener('click', function() {
    var feature = source.getFeatures()[0];
    var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
    var size = /** @type {ol.Size} */ (map.getSize());
    view.fit(polygon, size, {padding: [170, 50, 30, 150], constrainResolution: false});
  }, false);

  var zoomtoswitzerlandconstrained =
      document.getElementById('zoomtoswitzerlandconstrained');
  zoomtoswitzerlandconstrained.addEventListener('click', function() {
    var feature = source.getFeatures()[0];
    var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
    var size = /** @type {ol.Size} */ (map.getSize());
    view.fit(polygon, size, {padding: [170, 50, 30, 150]});
  }, false);

  var zoomtoswitzerlandnearest =
      document.getElementById('zoomtoswitzerlandnearest');
  zoomtoswitzerlandnearest.addEventListener('click', function() {
    var feature = source.getFeatures()[0];
    var polygon = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
    var size = /** @type {ol.Size} */ (map.getSize());
    view.fit(polygon, size, {padding: [170, 50, 30, 150], nearest: true});
  }, false);

  var zoomtolausanne = document.getElementById('zoomtolausanne');
  zoomtolausanne.addEventListener('click', function() {
    var feature = source.getFeatures()[1];
    var point = /** @type {ol.geom.SimpleGeometry} */ (feature.getGeometry());
    var size = /** @type {ol.Size} */ (map.getSize());
    view.fit(point, size, {padding: [170, 50, 30, 150], minResolution: 50});
  }, false);

  var centerlausanne = document.getElementById('centerlausanne');
  centerlausanne.addEventListener('click', function() {
    var feature = source.getFeatures()[1];
    var point = /** @type {ol.geom.Point} */ (feature.getGeometry());
    var size = /** @type {ol.Size} */ (map.getSize());
    view.centerOn(point.getCoordinates(), size, [570, 500]);
  }, false);

Typescript: Generate types from an object with the interface

It’s the second part for my question that was asked here. I’ve been helped with the solution for my previous problem, but once I added the interface for the alphabet object, Typescript stopped detecting that I provided the incorrect value.


interface ICharMap {
    lower: number
    upper: number
}

const alphabet: {[key: string]: ICharMap} = {
    'a': {lower: 97, upper: 65},
    'b': {lower: 98, upper: 66}
}

type Char = keyof typeof alphabet;

function printSome(char: Char){
    console.log(char)
}

printSome('c') \ Typescript does not detect that the incorrect value is passed.

React JS : grades.map is not a function

Can anyone help me, please?

I have grades array:

let grades=[];

I fill the grades array from another array:

 for(let i=0;i<restaurant.grades?.length;i++){
            grades+=restaurant.grades[i].grade;
        }

I have the following code:

<tbody>
    
    {grades.map((grade)=>
         <tr>
      
        <td>{grade}</td>
        
       </tr>
   )}
   
  </tbody>

I’m trying to print all grades from the grades array. [A,B,C,D].

I have error :

grades.map is not function

Can someone help me please figure it out?

Clear cache automatically in React.js

I use the below code to read text from resource (.json file) in the footer

${t("homePage.seRewarded.descriptionText.part6")}

But when I change it, the website needs clear cache to show it in the correct way, without clear cache show like below

homePage.seRewarded.descriptionText.part6

Can we have arrow function inside any object in Javascript? [duplicate]

const ob1 = {
  name: "siddharth",
  age: 19,
  myinfo: () => {
    console.log(`My name is ${this.name} and i am ${this.age}.`);
  }
}

ob1.myinfo();
const obj2 = {
  name: "pratham",
  age: 19
}

ob1.myinfo.call(obj2);

In the above code i practiced call method of javascript and it is working perfectly unless i replace normal function with call back functiond. Can anyone please explain me what’s the reason behind it.

How to Convert, in JS, an import statement to a require() statement

I have a Statement in JavaScript:

import app, { set } from '../app';

How can I write an equivalent statement in a form, such as I don’t get an error like ‘Cannot use import statement outside a module’.

I could convert similar less complex statement by using a format:
var Foo = require(foo);

but don’t understand how to convert this one.

How to manage errors on bulk update script with MongoDB and javascript?

I currently have a script that update datas on a website using api calls.
I loop through all the products in my database and I do my api calls to update the data on the website.

Sometimes an error occurs in the middle of the script execution so I’m not able to complete all the updates since I can’t go through all the products in the database.
And when I restart my script it always start from the beginning (first products in the database) so I’m never completing my bulk update .

How can I continue updates after an error occurred ?
For example, if error occurred at the product number 10, how can I keep doing the updates for the product number 11 without restarting my script from the beginning ? Is there a mongoDb function that tracks errors ?

I’m a beginner and I’m trying to understand the logics around bulk updates. I’ve thought about saving the ID of the products where the error occurred and then start updating after this ID. But, I’m sure there’s a standard procedure for managing bulk updates error and failures.

I’m using javascript, nodeJS and cron for my script.

I am trying to draw an sprite image in canvas with for loop to draw a complete colorful brick wall there is problem with loop

I am trying to draw an sprite image in canvas with for loop to draw a complete colorful brick wall there is problem with loop

 //variations    
 var sx = 0;
var sy = 0;
var sWidth = 82;
var sHeight = 31;
var px = 20;
var py = 20;
//draw image
function drawBricksImg(){
brickImg.src = "image/sprite_bricks.png";//get the image source
for(var i=0 ; i<10 ; i++){
sx +=sWidth;
px +=sWidth;
ctx.drawImage(brickImg, sx, sy, sWidth, sHeight, px, py,sWidth , sHeight);}

change selected value in msdropdown

I’m trying to use the msDropdown JavaScript plugin (https://github.com/marghoobsuleman/ms-Dropdown) to create html tags that include images.

It seems to work good except for if I try to change the selected value using JavaScript.
Like in this jsFiddle: https://jsfiddle.net/cmu845eh/7/
I’m trying to make it so that if you call the setValue() function, it will change the selected value to a certain index.

I’ve tried multiple different solutions online but none work, solutions such as this:

var oHandler = $("#main").msDropDown().data("dd");
oHandler.set("length", 0);

always result in an error, and more basic jquery approaches dont work either.

Can someone help me change the value of my select tag to a certain index using javascript?