Unwanted element shows up because of empty properties in an object

Using react.js

The code below represents two input boxes with a submit button. Clicking on the submit button will print the information typed inside of the two input boxes.

You can also remove those messages by clicking the delete button.

The initial state already contains an invincible string message and that makes an unwanted delete button appear initially. How can I remove this initial delete button and make sure that they only appear once the first “submit” is sent.

Any help would be appreciated, thank you!

import ReactDOM from 'react-dom';

class AddMessage extends Component {
    state = { title: null, body: null, }

    handleChange = (e) => {
        this.setState({ [e.target.id]: e.target.value })
    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.addMessage(this.state);
    }
    render() {
        return (<div>
            <form onSubmit={this.handleSubmit}>
                <label htmlFor="name">Title:</label>
                <input type="text" id="title" onChange={this.handleChange} />
                <label htmlFor="name">Body:</label>
                <input type="text" id="body" onChange={this.handleChange} />
                <button>Submit</button>
            </form>
        </div>)
    }
}

const Messages = (props) => {
    const { messages, deleteMessage } = props;
    const messageList = messages.map(message => {
        return (<div key={message.id}>
            <h3>{message.title}</h3>
            <h4>{message.body}</h4>
            <button onClick={() => deleteMessage(message.id)}>Delete</button>
        </div>)
    })

    return (<div>{messageList}</div>)
}

class TestTest extends Component {
    state = {
        messages: [{ title: "", body: "", id: 1 }]
    }
    addMessage = (message) => {
        message.id = Math.random();
        let messages = [...this.state.messages, message]
        this.setState({ messages: messages })
    }
    deleteMessage = (id) => {
        let messages = this.state.messages.filter(message => { return message.id !== id })
        this.setState({ messages: messages })
    }
    render() {
        return (
            <div>
                <Messages deleteMessage={this.deleteMessage} messages={this.state.messages} />
                <AddMessage addMessage={this.addMessage} />
            </div>
        )
    }
}

ReactDOM.render(<TestTest />, document.getElementById('root'));

export default TestTest```

Using regex with react hooks

I am basically trying to save the phone number entered by the user without braces, spaces or dashes but I somehow fail to do that. I am calling the regex after submitting the form in handleSubmit function through the setting of state and it prints out (and renders) without any change. Any idea what went wrong?

import React, { useContext, useState, useEffect } from "react";
import DataContext from "../store/data-context";

function Form() {
  const [name, setName] = useState("");
  const [secName, setSecName] = useState("");
  const [tel, setTel] = useState("");
  const [note, setNote] = useState("");
  const [state, setState] = useState({
    name: "",
    secName: "",
    tel: "",
    note: "",
  });
  

  const { dispatchDataState } = useContext(DataContext);

  const handleSubmit = (e) => {
    e.preventDefault();
    setTel((tel)=>tel.replace(/[^+d]+/g, ""))
    console.log(name);
    dispatchDataState({ type: "ADD_DATA", payload: state });
    setState(
      {
        name: "",
        secName: "",
        tel: "",
        note: "",
      }
    )
    console.log(state);
  };
  return (
    <div>
      <form onSubmit={handleSubmit}>
        <label>
          Jméno
          <input
            type="text"
            required
            value={state.name}
            onChange={(e) => setState({ ... state, name: e.target.value })}
          />
        </label>
        <label>
          Příjmení
          <input
            type="text"
            required
            value={state.secName}
            onChange={(e) => setState({ ... state, secName: e.target.value })}
          />
        </label>
        <label>
          Telefonní číslo
          <input
            type="text"
            required
            value={state.tel}
            onChange={(e) => setState({ ... state, tel: e.target.value })}
            
          />
        </label>
        <label>
          Poznámka
          <input
            type="text"
            value={state.note}
            onChange={(e) => setState({ ... state, note: e.target.value })}
          />
        </label>
        <input type="submit" value="Odeslat" />
      </form>
    </div>
  );
}

export default Form;

LuckyWheel – Show the Reward in a Div when the wheel lands on it

I am creating a little website/project for a friend. It’s a Lucky Wheel / Wheel of Fortune. I tried some premade script but none of them were like I needed and I thought that creating my own would be better.

I have made the actual Wheel in HTML / CSS. I already posted on Stack Overflow , got some help , advance the jscript part a bit but now i am missing only 1 thing. So my To Do list is as follows:

  • Have the wheel’s panel/li text (content) showed in my message box (where I have written “YOU JUST WON : XXXXXX”) once it lands on it.

FILENAME : wheel.php

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
  <meta http-equiv="x-ua-compatible" content="ie=edge" />
  <title>Material Design for Bootstrap</title>
  <!-- Favicon -->
  <link rel="icon" href="img/favicon.ico" type="image/x-icon" />
  <!-- Font Awesome 6 PRO -->
  <link rel="stylesheet" href="css/fontawesome/css/all.min.css" />
  <!-- Google Fonts Roboto -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500;700&display=swap" />
  <!-- MDB -->
  <link rel="stylesheet" href="css/mdb.min.css" />
  <!-- Custom styles -->
  <link rel="stylesheet" href="css/wheel.css">
  <!-- jQuery -->
  <script src="./js/jquery-3.6.0.min.js"></script>

</head>

<body class="bg-dark">

  <div class="container">
    <div class="row">
      <ul class="circle">
        <li>
          <div class="text">1</div>
        </li>
        <li>
          <div class="text">2</div>
        </li>
        <li>
          <div class="text">3</div>
        </li>
        <li>
          <div class="text">4</div>
        </li>
        <li>
          <div class="text">5</div>
        </li>
        <li>
          <div class="text">6</div>
        </li>
        <li>
          <div class="text">7</div>
        </li>
        <li>
          <div class="text">8</div>
        </li>
        <li>
          <div class="text">9</div>
        </li>
        <li>
          <div class="text">10</div>
        </li>
        <li>
          <div class="text">11</div>
        </li>
        <li>
          <div class="text">12</div>
        </li>
      </ul>
    </div>
    <div class="row justify-content-center mt-n4">
      <span class="spin_arrow"></span>
    </div>

    <!-- ### START ### MESSAGE BOX FOR REWARD : WILL SHOW ONLY WHEN A REWARD IS WON. -->
    <div class="message">
      <div class="row justify-content-center mt-4">
        <div class="col-md-8 bg-success text-white p-4 text-center">
          <h4>YOU JUST WON : XXXXXX</h4>
        </div>
      </div>
    </div>
    <!-- ### END ### MESSAGE BOX FOR REWARD : WILL SHOW ONLY WHEN A REWARD IS WON. -->

    <!-- ### START ### FORM FOR NUMBER OF SPINS + SUBMIT/SPIN BUTTON -->
    <div class="row justify-content-center mt-4">
      <div class="col-md-8 justify-content-center">
        <form action="#" method="POST" class="bg-light p-5">
          <div class="row justify-content-center">
            <div class="col-md-4 mb-4">
              <select class="select w-25" name="frm1_nbspin">
                <option value="1">1 Spin</option>
                <option value="2">2 Spins</option>
                <option value="3">3 Spins</option>
              </select>
              <label class="form-label select-label">Choose your Number of Spins</label>
            </div>
          </div>
          <div class="row justify-content-center">
            <div class="col-md-4 justify-content-center">
              <button type="submit" name="frm1_submit" id="frm1_submit" class="btn btn-block btn-primary">SPIN THE WHEEL</button>
            </div>
          </div>
        </form>
      </div>
    </div>
    <!-- ### END ### FORM FOR NUMBER OF SPINS + SUBMIT/SPIN BUTTON -->

  </div>

</body>

<!-- MDB -->
<script type="text/javascript" src="./js/mdb.min.js"></script>
<!-- WHEEL SPIN -->
<script type="text/javascript" src="./js/spinwheel.js"></script>

</html>

FILENAME : wheel.css

body {
  background: #2f2f2f;
}

.circle {
  position: relative;
  border: 1px solid black;
  padding: 0;
  margin: 1em auto;
  width: 25em;
  height: 25em;
  border-radius: 50%;
  list-style: none;
  overflow: hidden;
}

li {
  overflow: hidden;
  position: absolute;
  top: 0;
  right: 0;
  width: 50%;
  height: 50%;
  transform-origin: 0% 100%;
}

.text {
  position: absolute;
  left: -100%;
  width: 200%;
  height: 200%;
  text-align: center;
  -webkit-transform: skewY(60deg) rotate(15deg);
  -ms-transform: skewY(60deg) rotate(15deg);
  transform: skewY(60deg) rotate(15deg);
  padding-top: 20px;
  color: white;
  text-shadow: 1px 0 0 #000, 0 -1px 0 #000, 0 1px 0 #000, -1px 0 0 #000;
  font-size: 2em;
}

li:first-child {
  -webkit-transform: rotate(0deg) skewY(-60deg);
  -ms-transform: rotate(0deg) skewY(-60deg);
  transform: rotate(0deg) skewY(-60deg);
}

li:nth-child(2) {
  -webkit-transform: rotate(30deg) skewY(-60deg);
  -ms-transform: rotate(30deg) skewY(-60deg);
  transform: rotate(30deg) skewY(-60deg);
}

li:nth-child(3) {
  -webkit-transform: rotate(60deg) skewY(-60deg);
  -ms-transform: rotate(60deg) skewY(-60deg);
  transform: rotate(60deg) skewY(-60deg);
}

li:nth-child(4) {
  -webkit-transform: rotate(90deg) skewY(-60deg);
  -ms-transform: rotate(90deg) skewY(-60deg);
  transform: rotate(90deg) skewY(-60deg);
}

li:nth-child(5) {
  -webkit-transform: rotate(120deg) skewY(-60deg);
  -ms-transform: rotate(120deg) skewY(-60deg);
  transform: rotate(120deg) skewY(-60deg);
}

li:nth-child(6) {
  -webkit-transform: rotate(150deg) skewY(-60deg);
  -ms-transform: rotate(150deg) skewY(-60deg);
  transform: rotate(150deg) skewY(-60deg);
}

li:nth-child(7) {
  -webkit-transform: rotate(180deg) skewY(-60deg);
  -ms-transform: rotate(180deg) skewY(-60deg);
  transform: rotate(180deg) skewY(-60deg);
}

li:nth-child(8) {
  -webkit-transform: rotate(210deg) skewY(-60deg);
  -ms-transform: rotate(210deg) skewY(-60deg);
  transform: rotate(210deg) skewY(-60deg);
}

li:nth-child(9) {
  -webkit-transform: rotate(240deg) skewY(-60deg);
  -ms-transform: rotate(240deg) skewY(-60deg);
  transform: rotate(240deg) skewY(-60deg);
}

li:nth-child(10) {
  -webkit-transform: rotate(270deg) skewY(-60deg);
  -ms-transform: rotate(270deg) skewY(-60deg);
  transform: rotate(270deg) skewY(-60deg);
}

li:nth-child(11) {
  -webkit-transform: rotate(300deg) skewY(-60deg);
  -ms-transform: rotate(300deg) skewY(-60deg);
  transform: rotate(300deg) skewY(-60deg);
}

li:nth-child(12) {
  -webkit-transform: rotate(330deg) skewY(-60deg);
  -ms-transform: rotate(330deg) skewY(-60deg);
  transform: rotate(330deg) skewY(-60deg);
}

li:first-child .text {
  background: #FF3C38;
}

li:nth-child(2) .text {
  background: #ECC30B;
}

li:nth-child(3) .text {
  background: #E980FC;
}

li:nth-child(4) .text {
  background: #B96AC9;
}

li:nth-child(5) .text {
  background: #371E30;
}

li:nth-child(6) .text {
  background: #902D41;
}

li:nth-child(7) .text {
  background: #E57A44;
}

li:nth-child(8) .text {
  background: #8F5C38;
}

li:nth-child(9) .text {
  background: #7209B7;
}

li:nth-child(10) .text {
  background: #3A0CA3;
}

li:nth-child(11) .text {
  background: darkred;
}

li:nth-child(12) .text {
  background: gold;
}

.spin_arrow {
  color: #fff;
  font-size: 48px;
  text-align:center;
}

.spin_arrow::before {
  content: "2191";
}

FILENAME : spinwheel.js

$(function() {
  // Spin Counter, init as 0
  var spinCount = 0;
  var slices = [{
    label: "1",
    start: 0,
    end: 29
  }, {
    label: "2",
    start: 30,
    end: 59
  }, {
    label: "3",
    start: 60,
    end: 89
  }, {
    label: "4",
    start: 90,
    end: 119
  }, {
    label: "5",
    start: 120,
    end: 149
  }, {
    label: "6",
    start: 150,
    end: 179
  }, {
    label: "7",
    start: 180,
    end: 209
  }, {
    label: "8",
    start: 210,
    end: 239
  }, {
    label: "9",
    start: 240,
    end: 269
  }, {
    label: "10",
    start: 270,
    end: 299
  }, {
    label: "11",
    start: 300,
    end: 329
  }, {
    label: "12",
    start: 330,
    end: 359
  }]

  function spin(el) {
    var i = 0;
    // Select random Degree between 0 and 360
    var d = Math.floor(Math.random() * 360);
    // Reset Transform if already rotated
    if ($(el).css("transform") != "none") {
      console.log($(el).css("transform"), "Resetting to 0");
      $(el).css("transform", "rotate(0deg)");
    }
    console.log("Spin 720 + " + d + " degrees");
    // Animate Rotation of Element
    // Two full spins and then land on Random Degree
    $(el).animate({
      deg: 720 + d
    }, {
      duration: 3600,
      step: function(now, tween) {
        $(this).css({
          transform: 'rotate(' + now + 'deg)'
        });
      }
    }, function() {
      console.log("Complete Spin.", $(el).css("transform"));
    });
    // Calculate Slice Index (1 - 12)
    $.each(slices, function(k, o) {
      if (d >= o.start && d <= o.end) {
        i = k;
      }
    })
    console.log("Deg: " + d, "Index: " + i);
    return i;
  }

  function spinWheel() {
    //MAXIMUM SPINS CODE
    if (spinCount >= $("select[name='frm1_nbspin']").val()) {
      alert("No more Spins left");
      $("#frm1_submit").attr("disabled", true);
      return false;
    }
    spinCount++;
    //CODE FOR SPINNING THE WHEEL HERE...
    console.log("Spin #" + spinCount);
    console.log(spin(".circle"));
  }

  $("form").submit(function(event) {
    event.preventDefault();
    spinWheel();
  });
});

JSON type object only has parse and stringify methods, but I want to access the objects data

I have a project with NestJS, Typescript and Typeorm. I’m working with the following class Entity

class Event {
user: string,
createdAt: Date,
type: string,
data: JSON
}

In one of my methods I’m making a query to get some events, but I want to access just a few properties of the data attribute because the object has a lot information I don’t really need. The problem is that when I try to access the json, for example: receivedEvent.data.myProperty typescript tells me that this property is not available in type JSON. The only solution I can think of is changing the type of the data attribute to a string and parse it to json after the query, but I want to know if there is any other solution to this. This is the code I’m using to query the events:

async getLogs(loanId: string): Promise<Event[]> {
    const events = await this.eventRepository.find({
      select: ['createdAt', 'user', 'type', 'data'],
      where: {
        type: In([
          'early_payoff',
        ]),
        data: Raw(
          /* istanbul ignore next */
          () => 'data->"$.GUID" = :id',
          { id: loanId },
        ),
      },
      order: {
        id: 'DESC',
      },
    });

    console.log(events);

    
    return events.map(e=>{
      /// This is where my problem is
      const json: any = {"withdrawReason": e.data.withdrawReason}
      return {...e, data: json}
    });
  }

Anagram Javascript

Question with below code.
If I’m decreasing the object value and when it comes to zero how it is satisfying this condition if(!obj1[letter]) because letter still exist in obj, its value is just going down.

function validAnagram(a, b){
if(a.length !== b.length){
    return false;
}
if(a.length === 0 && b.length === 0 ){
    return true;
}
    let obj1 = {};

  // add whatever parameters you deem necessary - good luck!
    for(let i= 0; i<a.length; i++){
        if(obj1[a[i]]>0){
            obj1[a[i]]++
        }else{
                   obj1[a[i]] = 1;
        }
 

        
    }
    for(let i =0; i<b.length; i++){
        let letter = b[i];
        if(!obj1[letter]){
            return false
        } else {
            obj1[letter]--
        }
    }
    return true;
}



validAnagram('aza', 'zaz')

jquery document with not selector

I have some search fields on a page. Upon pressing ‘enter’ anything in these fields will then get filtered on for a dataset that’s displayed on a table.

$("document").on('keyup', (e) => {
    if (e.keyCode === 13) {
        searchAndDraw();
    }
});

My issue is that I have a table #myTable with some textareas in tds . Hitting ‘enter’ inside a textarea also triggers the search as the table is inside the document.

How can I apply this keyup event to the doc but exclude #myTable?

I tried $("document:not(#tliId)").on('keyup'... but that does not work.

Discord bot to kick users based on role

Good Afternoon,

first off I apologize for my lack of knowledge when it comes to Java Script. I am trying to fill a need for one of our servers without exactly knowing how 😀 The end goal is to kick a user once they received a specific role called “Inactive”.

Figure i’d start with creating a bot that kicks a user if you ‘kick @username’. These are the files I have:

Config.json:

{
"token": "(mytoken, which i'm obviously not posting :D)"
}

Index.js:

// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.once('ready', () => {
    console.log('Ready!');
});

client.on('message', message => {

    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'kick'){
        client.commands.get('kick').execute(message, args);
        }

});

client.login(token);

package.json:

{
  "name": "kickbyrole",
  "version": "1.0.0",
  "description": "Bot to kick based on discord role",
  "main": "index.js",
  "author": "Tri",
  "dependencies": {
    "@discordjs/builders": "^0.12.0",
    "@discordjs/rest": "^0.3.0",
    "discord-api-types": "^0.28.0",
    "discord-prefix": "^3.0.0",
    "discord.io": "^2.5.3",
    "discord.js": "^13.6.0",
    "winston": "^3.6.0"
  },
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "license": "ISC"
}

kick.js:

module.exports = {
    name: 'kick',
    description: "This command kicks a member!",
    execute(message, args){
        const target = message.mentions.users.first();
        if(target){
            const memberTarget = message.guild.members.cache.get(target.id);
            memberTarget.kick();
            message.channel.send("User has been kicked");
        }else{
            message.channel.send("You couldn't kick that member");
        }
    }
}

I can “node .” to initiate it without error. My bot shows online.. but nothing happens when I try to !kick @username.

Two asks.. a) what am I missing for my bot to work and b) what do I need to change for it to kick based off user role? So like ‘kick @role’

Appreciate all your time and help!

Cheers

Tri

Validations using if else and hasClass statements in Cypress

I am trying to validate the set of titles for a component. Below is my Cypress code snippet:

it('Validate the titles of all the tiles', () => {
    cy.get('.bms-scoreboard__game-tile')
      .each(($el) => {
        if($el.hasClass('bms-scoreboard__game-tile--cancelled')) {
            $el.get('.bms-scoreboard__game-tile-status--cancelled')
               .invoke('text')
               .then((text) => {
                  expect(text).equals('Cancelled')
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--pre-game')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                    const gameTime = text.split(" ").pop()
                    expect(['AM', 'PM']).to.include(gameTime)
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--final')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const finalTitle = text.trim()
                   expect(finalTitle).to.be.oneOf(['Final','Final (OT)'])
               })
        } else if($el.hasClass('bms-scoreboard__game-tile--ongoing')) {
            $el.get('.bms-scoreboard__game-time--en')
               .invoke('text')
               .then((text) => {
                   const ongoingTitle = text.trim()
                   expect(ongoingTitle).equals('Ongoing')
               })
        }
    })
})

But I get an error message: ‘Cannot read properties of undefined (reading ‘invoke’)’.

It works fine if I try it with only if block.

How can you efficiently update the fill of GeoJson polygons in MapboxGL?

I’m building an application that will render a map with a large GeoJSON set (around 3MB). The map is a choropleth, and the different GeoJSON polygons are meant to be colored differently depending on the data that they “contain.”

The problem I’m running into is that I’m unsure how to separate the GeoJSON (e.g. polygon data) from the actual data. Let’s say we set the data like this (or as Mapbox recommends, just via the URL to a data source):

const { data } = await axios.post(sourceUrl, settings);
map.current.addSource("states", {
  type: "geojson",
  data,
}

The underlying data in this map will need to update frequently with user interaction. However, right now the GeoJSON contains both the data for the polygons (coordinates) and the properties (the data itself).

For instance, the user might click a checkbox, or type in a search parameter. This currently makes a GET to our DB, which runs a query and returns the new data. We could return a new GeoJSON object with this data added inside of it and call a .getSource("source").setData(newData) will all of the new GeoJSON, but that would be terribly inefficient. The polygons aren’t changing, only the data they contain is.

I’ve looked into data-driven styling, but that doesn’t appear to be what I need either. Our underlying data set for the map is far too large to be crammed into a single GeoJSON layer, we can’t transfer hundreds of MBs over the network in order to apply data-driven styles on the client.

How can we render GeoJSON polygons to the map just once, and then update their fill colors depending on how a different data set is changed?

Hamburger menu not working when I change class name using UseState in React

I am creating a navigation bar for a website, and everything is working fine, and the hamburger menu when you change screen size. However, I also made my navbar fixed as the user scrolls.

The hamburger menu works fine when you are scrolled to the top, but once you start scrolling, the hamburger doesn’t click.

If I change the initial state of ‘false’ to ‘true,’ it will work in reverse order .. so it will not work when at the top, but it will work when scrolling.

I have been trying to figure this out all day, and I have been attempting to find a solution, but I could not. If anyone could help me, It would be greatly appreciated.

Hamburger menu at the top working

Hamburger menu at the top working

enter image description here

When I scroll down the hamburger menu doesn’t click anymore

enter image description here

Navbar code:

function Navbar2() {
  const [scrolled, setScrolled] = useState(false);

  const canvasRef = useRef();
  const navLinksRef = useRef();
  const liRefAbout = useRef();
  const liRefServices = useRef();
  const liRefGallery = useRef();
  const liRefTestimonials = useRef();
  const liRefContact = useRef();

  // toggle mobile menu on icon click
  useEffect(() => {
    const burger = canvasRef.current;
    const nav = navLinksRef.current;
    const aboutLink = liRefAbout.current;
    const servicesLink = liRefServices.current;
    const galleryLink = liRefGallery.current;
    const testimonialsLink = liRefTestimonials.current;
    const contactLink = liRefContact.current;

    burger.addEventListener('click', () => {
      nav.classList.toggle('nav-active');
      aboutLink.classList.toggle('list-about-active');
      servicesLink.classList.toggle('list-services-active');
      galleryLink.classList.toggle('list-gallery-active');
      testimonialsLink.classList.toggle('list-testimonials-active');
      contactLink.classList.toggle('list-contact-active');
      burger.classList.toggle('toggle');
    });
  }, [scrolled]);

  // make navbar fixed on scroll
  const handleScroll = () => {
    const offset = window.scrollY;
    if (offset > 80) {
      setScrolled(true);
    } else if (offset < 80) {
      setScrolled(false);
    }
  };
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });

  let x = ['navbar'];
  if (scrolled) {
    x.push('scrolled');
  }

  return (
    <nav className={`navbar ${scrolled ? 'scrolled' : ''}`}>
........

Navbar CSS

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 8vh;
  background: transparent;
  transition: all 0.4s linear;

  position: sticky;
  position: -webkit-sticky;
  top: 0;
  z-index: 900;
}

.scrolled {
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(6px);
  width: 100%;
}

please help me to solve hash table and explain it [closed]

In the hash table below we use open addressing with linear probing to resolve collisions.
The hash function is h(x)=x(mod11). In the table x denotes the places of deleted elements.

     0     1      2     3    4    5    6    7    8    9    10
     11   34     24     x         x    6         x         x

When inserting number 12 what is distance between its hash value and its final position?

Select one or more:

A- 10

B- 1

C- 4

D- 3

E- 9

The JavaScript ‘clearInterval’ function does not appear to be working. Can anyone help me?

I have the following code which adjusts the size of two panels, one above the other. Move the mouse up and the top panel will get smaller while the bottom panel will get larger. It all seems to work well enough, however, on mouseup although the ‘clearInterval’ line appears to be executed, ‘interval’ is not reset and movement of the mouse still alters the panel sizes.

Can anyone point out where I have gone wrong or indeed indicate a better way to do this?

Thanks in advance.

document.addEventListener('DOMContentLoaded',function(event){
  document.querySelector('#partition').onmousedown = function(event){
    //Set a timer to check every millisecond the position of the mouse and asign that position to the panels
    var interval=setInterval(function(){
      onmousemove = function(e){
        document.getElementById('topPanel').style.height = e.clientY;
        document.getElementById('btmPanel').style.height = viewport_height - e.clientY - 10;
      }
      //check for mouse up and cancel timer.
      onmouseup = function(){
        clearInterval(interval); 
      }
    }, 100); // the above code is executed every 100 ms  
  }
});

why innerHTML is not able to set the value of id = ‘result’ field to show the interest ..?

[i am not able to get the desired output of getting the simple interest….here innerhtml is not responding to set the value of id = ‘result’ field……here i have posted my code part..

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Document</title>
<script type="text/javascript">
    function fun1()
    {
      var a = document.getElementById('p').value ;
      var b = document.getElementById('n').value ;
      var c = document.getElementById('r').value ;
      var result = document.getElementById('result');

      result.innerHTML = "The interest is" + (p*n*r/100) ;
    }
</script>
</head>
<body>

<form name="form1">
    <label> Enter Principal amount :
        <input type="text" id="p"><br>
    </label>

    <label> Enter no. of years :
        <input type="text" id="n"><br>
    </label>

    <label> Enter rate  :
        <input type="text" id="r"><br>
    </label>
   
    <button type="submit" onclick="fun1()"> calculate </button>

    <p id="result">
   </p>
  </form>

  <script type="text/javascript">
 
  </script>

  </body>
  </html>

][1]

JS Array Reduce with Merging Duplicate Nested Array

I have an array like this:

var myArray = [
    {
        "name": "walkway_lights",
        "title": "Brilliance Sequoia Pathlight",
        "subCat": "Area & Pathway Lights",
        "cat": "Fixture-Speaker-Sub",
        "msrp": 599,
        "accTotal": 50,
        "purchasePrice": 222.35,
        "totalPrice": 1222,
        "totalPurchasePrice": 468.7,
        "lightShadowColor": "warmWhite",
        "wattage": {
            "key": "-Mm46mr5KHJwLXsucsJK",
            "upPrice": 12,
            "value": "3.5w G4"
        },
        "selectedAccessory": [
            {
                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                "name": "Demo 1",
                "price": 5
            },
            {
                "key": "-Mxa9NUjMExUd8b5UgfU",
                "name": "Demo 2",
                "price": 10
            },
            {
                "key": "-Mxa9Vh4yBK9j-GNpA0v",
                "name": "Demo 4",
                "price": 20
            }
        ],
        "beam": {
            "key": "-Mm4B0FO34Ineht5O0sw",
            "value": "360"
        }
    },
    {
        "name": "walkway_lights",
        "title": "Brilliance Sequoia Pathlight",
        "type": "group",
        "subCat": "Area & Pathway Lights",
        "cat": "Fixture-Speaker-Sub",
        "msrp": 599,
        "accTotal": 15,
        "purchasePrice": 222.35,
        "totalPrice": 626,
        "totalPurchasePrice": 249.35,
        "lightShadowColor": "warmWhite",
        "wattage": {
            "key": "-Mm46mr5KHJwLXsucsJK",
            "upPrice": 12,
            "value": "3.5w G4"
        },
        "selectedAccessory": [
            {
                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                "name": "Demo 1",
                "price": 5
            },
            {
                "key": "-Mxa9NUjMExUd8b5UgfU",
                "name": "Demo 2",
                "price": 10
            },
            ,
            {
                "key": "-Mxa9ZUjMExUd3g5Ugfs",
                "name": "Demo 3",
                "price": 15
            }
        ],
        "beam": {
            "key": "-Mm4B0FO34Ineht5O0sw",
            "value": "360"
        }
    }
]

I need to reformat “myArray” in such a way that it nest all objects based “subCat” and then “subCat” inside “cat”. In those nested children, I am converting duplicate objects based on “name + lightShadowColor + wattage.value + beam.value” and I am adding a variable “count” to remove duplicate objects. I am able to come up with a solution like below:

let result = [], counter = {};
for (let item of myArray) {
    let countId;
    if(item.lightShadowColor && item.wattage) {
    countId = item.name + item.lightShadowColor + item.wattage.value + item.beam.value
    } else {
    countId = item.name
    }
    let a = [];
    if (counter[countId]) {
    counter[countId].count++;
    counter[countId].totalPrice = counter[countId].count * (counter[countId].msrp + counter[countId].wattage.upPrice)
    counter[countId].totalPurchasePrice = counter[countId].count * (counter[countId].purchasePrice + counter[countId].wattage.upPrice);
    continue
    }

    let cat = result.find(o => o.cat == item.cat);
    if (!cat) result.push(cat = { cat: item.cat, children: [] });
    let subCat = cat.children.find(o => o.subCat == item.subCat);
    if (!subCat) cat.children.push(subCat = { subCat: item.subCat, children: [] });
    item.count = 1;
    subCat.children.push(counter[countId] = item);
}
console.log(result)

The above code gives me output which I desire as below:

result = [
    {
        "cat": "Fixture-Speaker-Sub",
        "children": [
            {
                "subCat": "Area & Pathway Lights",
                "children": [
                    {
                        "count": 2
                        "name": "walkway_lights",
                        "title": "Brilliance Sequoia Pathlight",
                        "subCat": "Area & Pathway Lights",
                        "cat": "Fixture-Speaker-Sub",
                        "msrp": 599,
                        "accTotal": 50,
                        "purchasePrice": 222.35,
                        "totalPrice": 1222,
                        "totalPurchasePrice": 468.7,
                        "lightShadowColor": "warmWhite",
                        "wattage": {
                            "key": "-Mm46mr5KHJwLXsucsJK",
                            "upPrice": 12,
                            "value": "3.5w G4"
                        },
                        "selectedAccessory": [
                            {
                                "key": "-Mxa9Jt-9si0Bw7Zhj1S",
                                "name": "Demo 1",
                                "price": 5
                            },
                            {
                                "key": "-Mxa9NUjMExUd8b5UgfU",
                                "name": "Demo 2",
                                "price": 10
                            },
                            {
                                "key": "-Mxa9Vh4yBK9j-GNpA0v",
                                "name": "Demo 4",
                                "price": 20
                            }
                        ],
                        "beam": {
                            "key": "-Mm4B0FO34Ineht5O0sw",
                            "value": "360"
                        }
                    }
                ]
            }
        ]
    }
]

Now, I am trying to figure out how should I merge “selectedAccessory” array for duplicate objects. Any idea how should I merge those keys? Inside the result, I need “selectedAccessory” array like this:

"selectedAccessory": [
    //The below come from myArray first duplicate object
    {
        "key": "-Mxa9Jt-9si0Bw7Zhj1S",
        "name": "Demo 1",
        "price": 5
    },
    {
        "key": "-Mxa9NUjMExUd8b5UgfU",
        "name": "Demo 2",
        "price": 10
    },
    {
        "key": "-Mxa9Vh4yBK9j-GNpA0v",
        "name": "Demo 4",
        "price": 20
    },
    //The below come from myArray second duplicate object
    {     
        "key": "-Mxa9Jt-9si0Bw7Zhj1S",
        "name": "Demo 1",
        "price": 5
    },
    {
        "key": "-Mxa9NUjMExUd8b5UgfU",
        "name": "Demo 2",
        "price": 10
    },
    ,
    {
        "key": "-Mxa9ZUjMExUd3g5Ugfs",
        "name": "Demo 3",
        "price": 15
    }
],