Accumulated in a structured object in Javascript [duplicate]

This is my data:

const data = [{
    "cluster": 1,
    "year": 2010
  },
  {
    "cluster": 1,
    "year": 2020
  },
  {
    "cluster": 1,
    "year": 2020
  },
  {
    "cluster": 2,
    "year": 2010
  },
  {
    "cluster": 3,
    "year": 2015
  }
];

I would like to have this as my result:

accumulatedData = [{
    "cluster": 1,
    years: [{
        year: 2010,
        frequency: 1
      },
      {
        year: 2020,
        frequency: 2
      }
    ]
  },
  {
    "cluster": 2,
    years: [{
        year: 2010,
        frequency: 1
      },
      {
        year: 2015,
        frequency: 0
      }
    ]
  },
  {
    "cluster": 3,
    years: [{
      year: 2015,
      frequency: 1
    }, {
      year: 2020,
      frequency: 0
    }]
  }
];

console.log(accumulatedData);

In words, I would like to:

  1. structure the data into the 3 clusters.
  2. add objects for each year within a specific cluster
  3. add the frequency of the occurence of a year in a specific cluster

I’ve realised that the reduce function might be useful here. I’ve managed to set the structure, but I am stuck in adding the values in the objects. Especially accumulating the number of times a year occurs in a particular cluster.

Am I on the right track, or would a for loop be better?

const data = [{
    "cluster": 1,
    "year": 2010
  },
  {
    "cluster": 1,
    "year": 2020
  },
  {
    "cluster": 1,
    "year": 2020
  },
  {
    "cluster": 2,
    "year": 2010
  },
  {
    "cluster": 3,
    "year": 2015
  }
];

var accumulatedData = {};

accumulatedData = data.reduce((a, b) => {
  a[b.cluster] = [{
    "year": 0,
    "frequency": 0
  }];
  a[b.cluster].year = b.year;
  a[b.cluster].frequency = a[b.cluster].frequency + 1;
  return a;
}, {})

console.log("accumulatedData", accumulatedData);

ISM format video not working for Dashjs in Vue 3

I am attempting to implement the Dashjs package for a Vue 3 video player, loosely based on the following: http://reference.dashif.org/dash.js/latest/samples/smooth-streaming/mss.html. So far, I have a simple video player view that I set up using Vue 3 with Dashjs.

<template>
  <div class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
    <div class="px-4 py-6 sm:px-0">
      <div :v-model="modelValue" :style="`height: ${height}; width: ${width};`">
        <video id="video" style="width:100%; height:100%;" controls></video>
        <button outlined @click="videoPlayer">Render Video</button>
      </div>
    </div>
  </div>
</template>
<script setup>

import { ref } from 'vue'
import { MediaPlayer } from 'dashjs'

const player = ref()

const videoPlayer = () => {
  player.value = MediaPlayer().create();
  const video = document.getElementById('video')
  player.value.initialize()
  player.value.attachView(video)
  player.value.attachSource('<video URL>')
  console.log([video, player.value])
}
</script>

for player.value.attachSource('<video URL>') I was able to run an mpd formatted video just fine. However, when I add links to ISM formatted videos, the player does not seem to recognize ISM formatted videos. How can I configure this code to recognize ISM formatted videos?

Here is an ISM formatted video that I tried using:

http://playready.directtaps.net/smoothstreaming/SSWSS720H264/SuperSpeedway_720.ism/Manifest

How do I crop a konva image when it has been resized?

In my project, I have a konva canvas where I can add items. I default these item images to a height and width of 200. When trying to apply a crop to the item, the crop ignores the resized image dimensions. It crops the image size to the correct height and width but the image itself returns back to its original dimensions. Is there an easy way to fix this? I saw this being asked KonvaJS crop and resize but that deals with a manual resizing of images.

image when loaded with
original dimensions 394 x 387 that is resized to 200 x 200 image in a 200 x 200 area

enter image description here

when trying to crop the image of 8 pixels, the image reverts back to 394 x 387 and crops to 386 x 387 in an image area of 192 x 200

enter image description here

addItem = (imgUrl) => {
    const img = new (window as any).Image();
    img.onload = () => {
      const width, height = 200;
      img.width = 200;
      img.height = 200;
      const newImg = new Konva.Image({ width, height, image: img, draggable: true });
      this.layer.add(newImg);
      this.layer.draw();
    };
    img.src = imageUrl;
  }

cropItem = (item) => {
    item.crop({
      x: item.cropX() + 8,
      y: item.cropY() + 0,
      width: item.width() - 8,
      height: item.height() - 0
    });

    item.width(item.width() - 8);
    this.layer.draw();
}

Edit polygon tiling program to allow me to draw polygon by hand

My code allows me to ’tile’ a polygon. Basically you designate the vertices of the polygon, the program then draws the polygon and then populates with tiles. In it’s present form, the user has to designate all the vertices before the program populates tile. I was wondering how I could edit the code such that the polygon could be drawn by the user before it populates with tiles.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <title>draw a line map</title>
    <style>
        /* Set the size of the div element that contains the map */
        #map {
            width: 100%;
            height: 80vh;
            position: relative;
            transform: translateZ(0px);
            border-radius: 5px;
        }

        #color-palette {
            clear: both;
        }

        .color-button {
            width: 30px;
            height: 30px;
            font-size: 0;
            margin: 2px;
            float: left;
            cursor: pointer;
            border-radius: 16px
        }

        .button_style {
            border-radius: 20px
        }

        .input_radius {
            border-bottom-right-radius: 20px;
            border-top-right-radius: 20px;
        }

        .input_radius_icon {
            border-bottom-left-radius: 20px;
            border-top-left-radius: 20px;
        }

        .padding_less {
            padding-left: 0px;
        }

        .margin_container {
            margin-top: 15px;
            margin-bottom: 15px;
        }

        .text-align_div {
            text-align: center;
        }

        #area {
            font-weight: bold;
        }

        .btn-info {
            box-shadow: 0 4px 2px -2px #555;
        }
        .disclaimer{
            display: none!important;
        }
    </style>

    <script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=geometry&key=AIzaSyCRtLFKkCMZlzTABau9Qbg9-iPLgp-GSCw&callback=initMap"></script>
    <script type='text/javascript'>
      var mapCanvas, boxes = new google.maps.MVCArray();
      function initialize() {
        var mapDiv = document.getElementById("map_canvas");
        mapCanvas = new google.maps.Map(mapDiv, {
          center : new google.maps.LatLng(38.8709, -77.0556),
          mapTypeId : google.maps.MapTypeId.SATELLITE,
          zoom : 19,
          tilt : 0
        });


        //Encoded path
        var paths = [
        [
          new google.maps.LatLng(38.872886, -77.05472),
          new google.maps.LatLng(38.872602, -77.058046),
          new google.maps.LatLng(38.87008, -77.058604),
          new google.maps.LatLng(38.868894, -77.055664),
          new google.maps.LatLng(38.870598, -77.053346),
        ],
      ];
        
        

        //Draw a polygon
        var polygonOpts = {
          paths : paths,
          strokeWeight : 6,
          strokeColor : "#FF0000",
          strokeOpacity : 1,
          //fillColor : "blue",
          fillOpacity : 0,
          map : mapCanvas,
          editable : true
        };
        var poly = new google.maps.Polygon(polygonOpts);


        var proc = function() {
          onPolygonComplete(poly);
        };
        google.maps.event.addListener(mapCanvas, "projection_changed", proc);
        google.maps.event.addListener(poly.getPath(), 'insert_at', proc);
        google.maps.event.addListener(poly.getPath(), 'remove_at', proc);
        google.maps.event.addListener(poly.getPath(), 'set_at', proc);
        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {

                    if (e.type != google.maps.drawing.OverlayType.MARKER) {
                        // Switch back to non-drawing mode after drawing a shape.
                        drawingManager.setDrawingMode(null);

                        // Add an event listener that selects the newly-drawn shape when the user
                        // mouses down on it.
                        var newShape = e.overlay;
                        newShape.type = e.type;

                        google.maps.event.addListener(newShape, 'click', function() {
                            setSelection(newShape);
                            updateLabelOfPolygon(newShape);
                        });

                         document.getElementById('calculate').addEventListener('click', function() {
                            google.maps.event.trigger(newShape, 'click');
                        });
                     
                       addLabelToNewShape(newShape);
                       
                       setSelection_without_area(newShape);
                    }
                });
      }

      function onDrawMgr_complete(polygon) {
        var path = polygon.getPath();
        console.log(google.maps.geometry.encoding.encodePath(path));
      }

      function onPolygonComplete(polygon) {
        var bounds, paths, sw, ne, ystep, xstep, boxH, boxW, posArry, flag, pos, x, y, i, box;

        //Delete old boxes.
        boxes.forEach(function(box, i) {
          box.setMap(null);
          delete box;
        });

        //Calculate the bounds that contains entire polygon.
        bounds = new google.maps.LatLngBounds();
        paths = polygon.getPath();
        paths.forEach(function(latlng, i) {
          bounds.extend(latlng);
        });

        var projection = mapCanvas.getProjection();
        var zoom = mapCanvas.getZoom();
        var powBase = Math.pow(2, zoom);

        //Calculate the small box size.
        sw = bounds.getSouthWest();
        ne = bounds.getNorthEast();
        var swPoint = projection.fromLatLngToPoint(sw);
        var nePoint = projection.fromLatLngToPoint(ne);
        var boxSize = new google.maps.Size(10, 20); //in pixels.
        boxSize.width /= powBase;
        boxSize.height /= powBase;
        var maxX = Math.floor(Math.abs((swPoint.x - nePoint.x)) / boxSize.width);
        var maxY = Math.floor(Math.abs((swPoint.y - nePoint.y)) / boxSize.height);


        for ( y = 0; y < maxY; y++) {
          for (x = 0; x < maxX; x++) {
            //Detect that polygon is able to contain a small box.
            bounds = new google.maps.LatLngBounds();
            posArry = [];
            posArry.push(new google.maps.Point(swPoint.x + boxSize.width * x, swPoint.y - boxSize.height * y));
            posArry.push(new google.maps.Point(swPoint.x + boxSize.width * x, swPoint.y - boxSize.height * (y + 1)));
            posArry.push(new google.maps.Point(swPoint.x + boxSize.width * (x + 1), swPoint.y - boxSize.height * y));
            posArry.push(new google.maps.Point(swPoint.x + boxSize.width * (x + 1), swPoint.y - boxSize.height * (y + 1)));

            var flag = true;
            for (var i = 0; i < posArry.length; i++) {
              pos = projection.fromPointToLatLng(posArry[i]);
              if (flag) {
                flag = google.maps.geometry.poly.containsLocation(pos, polygon);
                bounds.extend(pos);
              }
            }

            if (flag) {
              box = new google.maps.Rectangle({
                bounds : bounds,
                map : mapCanvas,
                strokeColor : 'green',
                strokeOpacity : 1,
                strokeWeight : 1,
                fillColor : 'green',
                fillOpacity : 0.5,
                clickable : false
              });
              boxes.push(box);
            }
          }
        }
      }


      google.maps.event.addDomListener(window, "load", initialize);
    </script>
    <style type="text/css">
      window,html,#map_canvas{
        width : 700px;
        height : 500px;
      }
    </style>
  </head>
  <body>

    

    <div id="map_canvas"/>
  </body>
</html>

JavaScript, canvas – drawn lines disappear after placing mouse over other element

my idea for the page is to load an image (done by <input type="file/>) and to draw some lines on it (those will represent spool points on welding map drawing.

I have tag in order to do that. However my current code is not working because I add canvas.addEventListener("mouseover", handler, false); event. Adding extra mouseout event doesn’t solve the problem. Lines disappear when mouse proceed event over other elements in document. I tried to add arrow function, or add document.addEventListener('DOMContentLoaded') event. Both are not helpful.

Please answer how to keep lines visible as long as file is loaded.
Moreover I have some problems adding event listeners to clear and undo buttons – my variable lines = []; seems to store more data that I expected. How should I prepare this feature to undo last drawn line?

HTML

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="https://unpkg.com/chota">
        <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    </head>
    <body>
        <h1 id="header" name="header">Spool assistant</h1>
        <div>
            <p>Click to draw lines</p>
        </div>
        <br/>

        <div id="main-area">
            <div id="draftsman-menu">
                <input type="button" id="file-selector-button" value="Load pdf" onclick="document.querySelector('#file-selector').click();" />
                <input type="file" id="file-selector" accept=".jpg, .jpeg, .png, .pdf" style="display:none;">
            </div>
            <div id="canvas-area">
                <canvas id="canvas" width=1000 height=400></canvas>
            </div>
            <div id="edit-menu">
                <button id="clear">Clear</button>
                <button id="undo">Undo</button>
                <button id="save">Save</button>
            </div>
        </div>

        <p id="status"></p>
        <img id="output" style="display:none;">
        
        <script type="text/javascript" src="../static/js/drawing_events.js"></script>
    </body>
</html>

JS

// constants and variables
const status = document.querySelector("#status");
const output = document.querySelector("#output");
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
var canvasOffset = $("#canvas").offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var startX, startY, mouseX, mouseY;
var isDown = false;
var lines = [];
var imageOpacity = 1;
const canvasPosition = canvas.getBoundingClientRect();
const clearButton = document.querySelector("#clear");
const undoButton = document.querySelector("#undo");
var imageData;


// start with image change event
if (window.FileList && window.File && window.FileReader) {
  document.getElementById("file-selector").addEventListener("change", event => {
  output.src = "";
  status.textContent = "";
  // allow only one file even if user selected more
  const file = event.target.files[0];
  // validations
  if (!file.type) {
    status.textContent = "Error: The File.type property does not appear to be supported on this browser.";
    return;
  };
  if (!file.type.match("image.*")) {
    status.textContent = "Error: The selected file does not appear to be an image."
    return;
  };
  const reader = new FileReader();
  reader.addEventListener("load", event => {
    output.src = event.target.result;
    output.onload = function() {
      lines = [];
      ctx.drawImage(output, 0, 0);
    };
  });
  reader.readAsDataURL(file);
  });
};


// drawing events
canvas.addEventListener("mouseover", handler, false);

function handler(event) {
  var img = new Image();
  img.onload = start;
  img.src = output.src;

  function start() {
      canvas.width = canvas.width = img.width;
      canvas.height = img.height;
      ctx.strokeStyle = "black";
      ctx.lineWidth = 3;

      $("#canvas").mousedown(function(e){handleMouseDown(e);});
      $("#canvas").mousemove(function(e){handleMouseMove(e);});
      $("#canvas").mouseup(function(e){handleMouseUp(e);});
      $("#canvas").mouseout(function(e){handleMouseUp(e);});

      // redraw the image
      drawTheImage(img, imageOpacity);
  };

  function drawLines(toX, toY) {
      // clear the canvas
      ctx.clearRect(0, 0, canvas.width, canvas.height);

      // redraw the image
      drawTheImage(img,imageOpacity);

      // redraw all previous lines
      for(var i = 0; i < lines.length; i++) {
          drawLine(lines[i]);
      };

      // draw the current line
      drawLine({x1:startX,y1:startY,x2:mouseX,y2:mouseY});
  };

  function drawTheImage(img, opacity) {
      ctx.globalAlpha = opacity;
      ctx.drawImage(img, 0, 0);
      ctx.globalAlpha = 1.00;
  };

  function drawLine(line){
      ctx.beginPath();
      ctx.moveTo(line.x1, line.y1);
      ctx.lineTo(line.x2, line.y2);
      ctx.stroke();
  };

  function handleMouseDown(e){
    e.stopPropagation();
    e.preventDefault();
    mouseX = parseInt(e.clientX - canvasPosition["x"] + window.scrollX);
    mouseY = parseInt(e.clientY - canvasPosition["y"] + window.scrollY);

    // Put your mousedown stuff here
    startX = mouseX;
    startY = mouseY;
    isDown = true;
  };

  function handleMouseUp(e) {
    e.stopPropagation();
    e.preventDefault();

    // Put your mouseup stuff here
    isDown = false;
    lines.push({x1:startX, y1:startY, x2:mouseX, y2:mouseY});
  };

  function handleMouseMove(e) {
    if (!isDown) {return;}
    e.stopPropagation();
    e.preventDefault();
    mouseX = parseInt(e.clientX - canvasPosition["x"] + window.scrollX);
    mouseY = parseInt(e.clientY - canvasPosition["y"] + window.scrollY);

    // Put your mousemove stuff here
    drawLines(mouseX, mouseY);
  };


  // clearing
  // TODO
  // function has to be replaced with undoing or loading blank page
  function clearCanvas() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      lines = []
  };

  function undoLine() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawTheImage(img, imageOpacity);
      lines.pop();
      for(var i = 0; i < lines.length; i++) {
        drawLine(lines[i]);
    };
  };
  clearButton.addEventListener("click", clearCanvas);
  undoButton.addEventListener("click", undoLine);
};

Running Tone.js in Ace Code Editor loop is duplicating

I am making a tutorial on how to learn JavaScript using Tone.js. I am using the Ace editor to run the code in. Everything is working but every time you press play it doubles that sound each time causing distortion.

I tried to use ace’s editor.setValue(''); to clear the value on stop but that remove everything from the code editor. I need to clear the value from the script but leave it in the editor div. Not sure what I can do here.

const editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.session.setMode("ace/mode/javascript");
editor.setOptions({fontSize:"14pt"});
const go = () => {

const userCode = editor.getSession().getValue();

try {
    new Function(userCode)();
    console.log(userCode);
} catch (err) {
    console.error(err);
}
    Tone.Transport.start();
}
const stop = () => {
    Tone.Transport.stop();
}
#editor {
    width: 100%;
    height: 91%;
    position: relative;
    min-height: 500px;
}
.run {
    display: inline-block;
    width: 100px;
    height: 30px;
    background-color: #f0f0f0;
    border-radius: 4px;
    text-align: center;
    line-height: 20pt;
    font-weight: 900;
    cursor: pointer;
    margin: 0 11px 11px 0;
}
#go {
margin-left: 0;
}
.run:hover {
background-color: #75e9e9;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/tone/13.8.9/Tone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.4/ace.js"></script>
<div>
<div id="go" class="run" onclick="go()">Play</div>
<div id="stop" class="run" onclick="stop()">Stop</div>
</div>
    
<div id="editor">
const synth = new Tone.Synth();
synth.toMaster();
// C major cord
const notes = [
"C4", "E4", "G4",
"C5", "E5", "G5"
];
var index = 0;

Tone.Transport.scheduleRepeat((time) => {
    repeat(time);
}, '8n');

function repeat(time) {
    let note = notes[index % notes.length];
    synth.triggerAttackRelease(note, '8n', time);
    index++;
}
</div>

</div>

Modal not responsive to parent state change

I have a modal which intakes data and displays some of this data on a modal where a user can interact with it. The data is set and the modal is opened through my Starters component via the handleAdd function. The modal then consumes the homeData, set within the handleAdd function. However, upon opening the modal, I see original data from homeData‘s original state and I do not see the new homeData state set by setHomeData in the handleAdd function. This is odd because my modal does in fact tell me that homeData is the data that handleAdd/setHomeData sets it to when logging this in the modal.

Why is the original data being displayed on the modal instead of new data that I pass into it? How do I fix this?

Here’s the code:

Starters, the code that handles the setHomeData call in handleAdd

  const Starters = ({item}) => {
    const handleAdd = (data) => {
      setHomeData(data);
      showHomeModal()
    };

    const data = {
      Name: item.title,
      Stack: item.stack,
      ScheduleName: item.subtitle,
      Track: true,
      TrackString: "true",
    }

    return (
      <Card
        style={{
          marginRight: 10,
          marginBottom: 6
        }}
      >
        <Card.Title
          title={item.title}
          subtitle={`Schedule: ${item.subtitle}`}
          right={() =>
            <IconButton
              icon="plus-circle"
              color="#5F9DA5"
              onPress={() => handleAdd(data)}
            />
          }
          rightStyle={{
            marginBottom: 22
          }}
        />
        // rest of card stuff...
  }

In my HomeScreen I have Starters being rendered like so:

const HomeScreen = () => {
  // some default data
  const [homeData,setHomeData] = useState({
    "ScheduleName": "Everyday",
    "Stack": [
      {
        "amount": "3900",
        "measure": "mg",
        "substance": "Omega3",
        id: "7846365hjbvbert674t"
      },
      {
        "amount": "25",
        "measure": "mg",
        "substance": "B12",
        id: "8r76438hjvfguy"
      },
      {
        "amount": "2",
        "measure": "Tablets",
        "substance": "B-complex",
        id: "783657345634hgvbhjvh"
      },
    ],
    "Name": "Example",
    "Track": false,
    "TrackString": "false",
    "StartDate": new Date().toISOString()
  });
  // data that handleAdd should be setting for the modal
  const itemData = {  
    "Vits": {
      title: "Morning Essentials",
      subtitle: "Everyday",
      stack: [
        {
          substance: "Omega3",
          amount: "3900",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "B12",
          amount: "25",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "B-complex",
          amount: "2",
          measure: "Tablets",
          id: uuidv4()
        }
      ]
    },
    "Vits2": {
      title: "Evening Essentials",
      subtitle: "Everyday",
      stack: [
        {
          substance: "Vitamin C",
          amount: "500",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "Calcium Citrate",
          amount: "500",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "D3",
          amount: "16000",
          measure: "IU",
          id: uuidv4()
        },
        {
          substance: "Magnesium",
          amount: "80",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "Zinc",
          amount: "10",
          measure: "mg",
          id: uuidv4()
        },
        {
          substance: "Multi-vitamin",
          amount: "1",
          measure: "Tablets",
          id: uuidv4()
        }
      ]
    }
  }
  ...
  return (
  ...
      <Portal>
        <HomeStarterModal
          homeModalVisible={homeModalVisible}
          homeData={homeData}
          hideHomeModal={hideHomeModal}
        />
      </Portal>
  ...
      <ScrollView
        horizontal={true}
        style={{
          padding: 6,
          paddingHorizontal: 10
        }}
      >
        <Starters
          item={itemData["Vits"]}
        />
        <Starters
          item={itemData["Vits2"]}
        />
      </ScrollView>
  ...
)

Use TypeScript declaration in corresponding JavaScript file

I’ve started learning typescript, but it’s classic concept where both types and runtime code is inside one ts file doesn’t seem particularly attractive to me. Instead I’d like to keep writing javascript as before but add to my modules d.ts files with typings for type checks, hints, etc..

So, as I see, when importing some js + d.ts couple into js file with enabled checkJs option typescript will check that file for correct type usage based on d.ts file. But what I also need is the same behavior for imported js module itself. I.e. make typescript know values of what types my js module is recieving, check correct usage of that types and check that module is implements declaration.

Sounds a bit confusing, I know, so let me describe with example:

// a.d.ts
export function a(val: string): string;
// a.js
// Correct module implementation
export function a(val) {
    return `Hello ${val}`;
}
// a.js
// There must be two errors:
// argument is a string that doesn't have a "toFixed" method,
// and function return type is not a string anyway
export function a(val) {
    return {val: val.toFixed()};
}

This is behavior that I would like to see, but not what actually happens. Because actually happens nothing; typescript doesn’t use information from a.d.ts for a.js.

I’ve searched through https://www.typescriptlang.org/docs and doesn’t seem to find anything helpful. Is it even possible? If it, how to achieve such behavior?

i have an issue : Failed to execute ‘insertBefore’ on ‘Node’: The node before which the new node is to be inserted is not a child of this node

It works perfectly for the first time when i click on the pen icon for changing the name but when I click it for second time, it throws this error. I tried parentNode.insertBefore() but it doesn’t work as well

Here is my index.js code for edit button functionality

    const taskEdit = document.getElementById('taskName'); #its just a div with a default text

function edit() {
  if (editBtn.classList.contains('fa-pen-line')) {
    const input = document.createElement('input');
    input.type = 'text';
    input.setAttribute('id', 'edited');
    input.classList =
      'bg-transparent border-0 border-b-2 border-gray-300 appearance-none focus:outline-none focus:ring-0 focus:border-0';
    input.value = span.textContent;
    taskEdit.insertBefore(input, span);
    taskEdit.removeChild(span);
    editBtn.classList.replace('fa-pen-line', 'fa-check');
  }
  editBtn.addEventListener('click', () => {
    if (editBtn.classList.contains('fa-check')) {
      const input = document.getElementById('edited');
      const span = document.createElement('span');
      span.textContent = input.value;
      span.setAttribute('id', 'task');
      taskEdit.insertBefore(span, input);
      taskEdit.removeChild(input);
      editBtn.classList.replace('fa-check', 'fa-pen-line');
    }
  });
}
editBtn.addEventListener('click', edit);

1

Here is an image for the same, when i click pen con to change the name, it successfully changes it for the first time but gives me this DOMexception error if i try to change it again

rock/paper/scissors game outputting random results and I have no idea why

enter image description here

const gameElements = ['rock', 'paper', 'scissors'];
function computerPlay() {
            
    let elementsRun = gameElements[Math.floor(Math.random()*gameElements.length)];
    return elementsRun;
}


let playerScore = document.querySelector('.playerScore');
let computerScore = document.querySelector('.computerScore');
let playRounds = ''
let compRounds = ''






   





        
    
        
        function singleRound(playerSelection, computerSelection) {
            if (playerSelection === computerSelection) {
                return "It's a draw!"
            }
            else if (playerSelection === 'rock' && computerSelection === 'scissors') {
                playRounds ++;
                return "You win! Rock beats scissors"
            }
            else if (playerSelection === 'paper' && computerSelection == 'rock') {
                playRounds ++;
                return "You win! Paper beats rock"
            }
            else if (playerSelection === 'scissors' && computerSelection == 'paper') {
                playRounds ++;
                return "You win! Scissors beat paper"
            }


            else if (playerSelection === 'scissors' && computerSelection === 'rock') {
                compRounds ++;
                return "You lose! Rock beat scissors"
            }
            else if (playerSelection == 'paper' && computerSelection == 'scissors') {
                compRounds ++;
                return "You lose! Scissors beat paper"
            }
            else if (playerSelection === 'rock' && computerSelection === 'paper') {
                compRounds ++;
                return "You lose! Paper beat rock"

                
            }
        }
            
const buttonRock = document.querySelector('.rock')
buttonRock.addEventListener('click', function() {
    computerSelection = computerPlay();
    playerScore.innerHTML = 'Player:' + playRounds;
    computerScore.innerHTML = 'Computer:' + compRounds;
    const result = singleRound('rock', computerSelection)
    console.log(result)
});

const buttonPaper = document.querySelector('.paper')
buttonPaper.addEventListener('click', function() {
    computerSelection = computerPlay();
    playerScore.innerHTML = 'Player:' + playRounds;
    computerScore.innerHTML = 'Computer:' + compRounds;
    const result = singleRound('paper', computerSelection)
    console.log(result)
    
});

const buttonScissors = document.querySelector('.scissors')
buttonScissors.addEventListener('click', function() {
    computerSelection = computerPlay();
    playerScore.innerHTML = 'Player:' + playRounds;
    computerScore.innerHTML = 'Computer:' + compRounds;
    const result = singleRound('scissors', computerSelection)
    console.log(result)
   
    
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>rockpapergame</title>
        <link rel="stylesheet" href="./styles/style.css">

        <body>
    <div class="choices">
      <div class="buttons">
          <div class="tekst">
        <button class="rock"><span>Rock</span></button>
        <span class="playerScore">Player:</span>
    </div>
    <div class="tekst">
        <button class="paper"><span>Paper</span></button>
        <span class="winnerScore">Winner</span>
    </div>
    <div class="tekst">
        <button class="scissors"><span>Scissors</span></button>
        <span class="computerScore">Computer:</span>
    </div>
      </div>
    </div>

    

I want my buttons to interact with javascript, so I added eventlisteners to them. The weird thing is when for example: I click a button ‘rock’ and the output is ‘You win! Rock beats scissors’ but I don’t get a point. I will get a point if I click a random button again. Next example: Computer wins and computer doesn’t get a point and let’s say next click is a draw and then computer gets the point. I have no idea why.

Wait until WebGL has drawn onto screen

I switched from using 2D context to using WebGL context. I’m trying to figure out a way to wait until pixels have been drawn onto the screen.

With 2D context I would do something like this

const handlePaintFrame = () => {
  const ctx: CanvasRenderingContext2D | any = videoCanvasRef?.current?.getContext("2d");

  if (video.current && videoCanvasRef.current && ctx) {
    if (chroma?.keyColor) {
      drawChromaFrame(ctx, width, height);
    } else {
      ctx.drawImage(video.current, 0, 0, width, height);
    }

    const rendered = () => {
      setTimeout(() => {
        onReady("video");
      }, 20);
    };

    const startRender = () => {
      requestAnimationFrame(rendered);
    };

    const img = new Image();

    img.onload = () => {
      requestAnimationFrame(startRender);
    };

    img.onerror = (e: any) => {
      console.log("Image error:", { e });
    };

    img.src = videoCanvasRef.current.toDataURL();
  }
};

Currently my draw code for the WebGL context is something like this

const drawTexture = () => {
  // render
  if (gl && video.current) {
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, video.current);
    drawScene(locationRef.current, buffersRef.current);
  }
};

const handlePaintFrame = () => {
  if (video.current) {
    if (chroma?.keyColor) {
      // drawChromaFrame(ctx, width, height);
    } else {
      drawTexture();

      // TODO: We need to wait until texture is drawn
      setTimeout(() => {
        onReady("video");
      }, 100);
    }
  }
};