Timer loop instead of click event

Here’s a flip card that works on lick but I’d like to use a timer instead of click event. The idea is that the card is flipped every 5 seconds without clicking. Is there a way where click function can be swapped with a timer/loop without affecting the entire function or structure?

var card = document.querySelector('.card');
    card.addEventListener( 'click', function() {
      card.classList.toggle('is-flipped');
    });
.scene {
      width: 200px;
      height: 260px;
      border: 1px solid #CCC;
      margin: 40px 0;
      perspective: 600px;
    }
    
    .card {
      width: 100%;
      height: 100%;
      transition: transform 1s;
      transform-style: preserve-3d;
      cursor: pointer;
      position: relative;
    }
    
    .card.is-flipped {
      transform: rotateY(180deg);
    }
    
    .card__face {
      position: absolute;
      width: 100%;
      height: 100%;
      line-height: 260px;
      color: white;
      text-align: center;
      font-weight: bold;
      font-size: 20px;
      -webkit-backface-visibility: hidden;
      backface-visibility: hidden;
    }
    
    .card__face--front {
      background: green;
    }
    
    .card__face--back {
      background: gray;
      transform: rotateY(180deg);
    }
<div class="scene scene--card">
      <div class="card">
        <div class="card__face card__face--front">some text on the front</div>
        <div class="card__face card__face--back">some text on the back</div>
      </div>
    </div>
    <p>Click card to flip.</p>

How do I replace text inside a paragraph inside a div element?

I need to set the text within a Paragraph that is within a DIV element dynamically. I know the divID and can get the div by id using get document.getElementById(divID)
This returns the following:

<div id="mynote72031" class="mydiv" ondrop="drop(event,this.id)" ondragover="allowDrop(event)" style="cursor: move; display: block; top: 19px; left: 19px; width: 375px;">
  <a style="top:0px; right:5px;  position:absolute; color:#F00" href="javascript:;" onclick="hideElement(this)">X</a>
  <p id="noteContent1" ondblclick="editContent(this)">Note Number: 1</p>
</div>

The function should look like this:

function updateNote(divID, paragraphInnerHTML) {
  var updateNoteP = document.getElementById(divID);
  //Update Paragraph inside the DIV here
}

Note that the id of the paragraph is always noteContent1

Is ‘res.writeHead’ necessary? Does it have a purpose?

I am writing a bare minimal node.js server to understand how it works. From what I can tell this line:

res.writeHead(200);

does nothing. If I remove it I get the exact same behavior from the browser. Does it have any purpose? Is it OK to remove it?

// https://nodejs.dev/learn/the-nodejs-http-module

const http = require('http');
const server = http.createServer(handler);

server.listen(3000, () => {
  console.log('node: http server: listening on port: ' + 3000);
});

function handler(request, response) {
  res.writeHead(200);
  res.end('hello worldn');
}

Is it some how related to http headers?

JSON object hierarchy from XML document using JavaScript

Given an XML document such as this:

<Root> 
    <Child1 >
        <ChildOfChild1_1> </ChildOfChild1_1>
            <FinalChild> </FinalChild>
        <ChildOfChild1_2> </ChildOfChild1_2>
    </Child1>
    <Child2>
        <ChildOfChild2_1> </ChildOfChild2_1>
    </Child2>
    <Child3> </Child3>
</Root>

I would like to return a JSON object which has only two parameters, name and children. It would look like:

{
    name: "Root"
    children: [
        {
            name: "Child1"
            children: [
                {
                    name: "ChildOfChild1_1"
                    children:[
                        {
                            name: "FinalChild"
                            children: null
                        }
                    ]
                },
                {
                    name: "ChildOfChild1_2"
                    children: null
                }

            ]
        }, 
        {
            name: "Child2"
            children: [
                {
                    name: "ChildOfChild2_1"
                    children: null
                }
            ]
        }, 
        {
            name: "Child3"
            children: null
            ]
        }, 
    ]
}

I do not care about node attributes, only nodeName and if they have children. I wrote code to get the first level of children but cannot wrap my head around the recursive part to get as deep as necessary. Thanks.
Below is what I have so far:

//assuming block is the root node and the root will at least have 1 child
let root = {
    name = '',
    children = []
};
root.name = block.nodeName;

for(let i=0 ; i<block.children.length ; i++) {
    root.children.push(getChildren(block.children[i]));
}

function getChildren(data) {
let child = {};
child.name = data.nodeName;
child.children = []; //stuck here
    
return child;

}

How do I set the correct breakpoint for v-main in vuetify? (or remove the left padding on v-main)

I have a very typical application with a sidebar that collapses when the display width gets small, then uses a bottom drawer for smaller viewports. The issue I am seeing is thet the padding on v-main is 256 until the breakpoint gets to be sm. How can I change this padding?

This is the collapsed menu with the 256px padding, between sm and large:

This is the collapsed menu with the 256px padding, between sm and large

This is the screen at full width:

This is the screen at full width

“MathJax.texReset is not a function at window.RenderOutput” error in MathJax

I am getting the error MathJax.texReset is not a function
at window.RenderOutput most times in my MathJax. But sometimes it works fine without any edits.
my code is as below.

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/a_style.css">
    <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
    <script src="js/MathJax/es5/tex-chtml-full.js" charset="utf-8" async></script>
  </head>

at end i added some JS

<script src="js/jquery-3.6.0.min.js" charset="utf-8"></script>
<script src="js/bootstrap.bundle.min.js" charset="utf-8"></script>
<script src="js/mathjaxconfig.js" charset="utf-8" async id="MathJax-script"></script>
<script src="js/main.js" charset="utf-8"></script>

mathjaxconfig.js is

window.MathJax = {
loader: {load: ['input/asciimath','[tex]/physics']},
startup: {
ready:function() {
  const {Configuration} = MathJax._.input.tex.Configuration;
  const CommandMap = MathJax._.input.tex.SymbolMap.CommandMap;
  const TexError = MathJax._.input.tex.TexError.default;

  const CheckDimen = function (dimen) {
    if (dimen === '') return '';
    if (dimen.match(/^s*([-+]?(.d+|d+(.d*)?))s*(pt|em|ex|mu|px|mm|cm|in|pc)s*$/)) {
      return dimen.replace(/ /g, '');
    }
    throw new TexError('BadImageDimen', 'Bad dimension for image: %1', dimen);
  };
  new CommandMap('img', {img: 'Img'}, {
    Img(parser, name) {
      const arg = parser.GetBrackets(name, '');
      const def = {
        valign: '',
        width:  '',
        height: ''
      };
      if (arg.match(/[,=]/)) {
        for (const pair of arg.split(/s*,s*/)) {
          const [key, ...value] = pair.split(/s*=s*/);
          if (!def.hasOwnProperty(key)) throw new TexError('UnknownKey', 'Unknown parameter "%1" in %2', key, name);
          def[key] = CheckDimen(value.join('='));
        }
      } else {
        def.valign = CheckDimen(arg);
        def.width  = CheckDimen(parser.GetBrackets(name, ''));
        def.height = CheckDimen(parser.GetBrackets(name, ''));
      }
      def.src = parser.GetArgument(name);
      if (!def.valign) delete def.valign;
      if (!def.width)  delete def.width;
      if (!def.height) delete def.height;
      parser.Push(parser.create('token', 'mglyph', def));
    }
  });
  Configuration.create('img', {handler: {macro: ['img']}});

  MathJax.startup.defaultReady();
},
pageReady: function () {
    var input = document.getElementById('MathInput');
    var output = document.getElementById('MathPreview');
    var button = document.getElementById('renderHTML');
    //output.innerHTML = input.value.trim();
    window.typesetInput = function () {
      button.disabled = true;
      output.innerHTML = input.value.trim();
      MathJax.texReset();
      MathJax.typesetClear();
      MathJax.typesetPromise([output]).catch(function (err) {
        output.innerHTML = '';
        output.appendChild(document.createTextNode(err.message));
        console.error(err);
      }).then(function () {
        button.disabled = false;
      });
    }
    // input.oninput = typesetInput;
  // }

  return MathJax.startup.defaultPageReady();
}
},
tex: {
inlineMath: [['$', '$'], ['\(', '\)']],
processEscapes: true,
packages: {'[+]': ['img'],'[+]': ['physics']},
tags:'ams'
},
options: {
  enableMenu: false,
  menuOptions: {
    settings: {
      renderer: 'SVG'
    }
 }
}
};

and main.js is

window.RenderOutput = function (button,input,output) {
  var input=document.getElementById(input);
  var output=document.getElementById(output);
  button.disabled = true;
  output.innerHTML = input.value.trim();
  MathJax.texReset();
  MathJax.typesetClear();
  MathJax.typesetPromise([output]).catch(function (err) {
    output.innerHTML = '';
    output.appendChild(document.createTextNode(err.message));
    console.error(err);
  }).then(function () {
    button.disabled = false;
  });
}

window.RenderOutputFun = function (button,x) {
  var input=document.getElementsByClassName('op')[x];
  var output=document.getElementsByClassName('opPreview')[x];
  button.disabled = true;
  output.innerHTML = input.value.trim();
  MathJax.texReset();
  MathJax.typesetClear();
  MathJax.typesetPromise([output]).catch(function (err) {
    output.innerHTML = '';
    output.appendChild(document.createTextNode(err.message));
    console.error(err);
  }).then(function () {
    button.disabled = false;
  });
}

i can’t figure out why this happen. Because it works sometimes and shows error sometimes (mostly error).

Como puedo setear el objeto dentro de un formulario reactivo obtenido en un ngFor en Angular? [closed]

Aframe JS Error Could not load module ‘../GetIntrinsic’

After running npm start I receive the following error:

error: Processing of node_modules/aframe/dist/aframe-master.js failed. Error: Could not load module '../GetIntrinsic' from '/root/immerso-experience/node_modules/aframe/dist'. Make sure the file actually exists.

Here is the package.json

{


"name": "experience-engine",
  "description": "Immerso Experience Engine",
  "private": true,
  "author": "Immerso",
  "homepage": "https://immerso.io",
  "version": "1.3.0",
  "scripts": {
    "start": "export DEVELOPMENT=true && brunch w -n -s -P 3000",
    "build": "rm -rf public/ && brunch build --production && node -e 'require("./post-build.js").readWriteSync()'",
    "preinstall": "npx npm-force-resolutions || echo"
  },
  "jest": {
    "globals": {
      "$PROCESS_ENV_API_URL": "https://api.immersotours.com",
      "$PROCESS_ENV_WS_API_URL": null,
      "$PROCESS_ENV_RECAPTCHA_KEY": null,
      "$PROCESS_ENV_PAYPAL_CLIENT_ID": "ARbzpX1BmPBEJ37OXso7sdXACVyufeAZ4ovJLziEILohedwfwNNvXIpelUJSG64U65QjDn_lfXHa4P3E",
      "$PROCESS_ENV_AES_KEY": "secret-key",
      "$PROCESS_ENV_DEVELOPMENT": true
    }
  },
  "dependencies": {
    "aframe": "^1.3.0",
    "aframe-event-set-component": "^3.0.3",
    "aframe-fit-texture-component": "^0.2.5",
    "aframe-look-at-component": "1.0.0",
    "aframe-particle-system-component": "^1.1.3",
    "aframe-react": "^4.4.0",
    "aframe-scene-look-controls": "^1.0.5",
    "aframe-video-controls": "^0.3.0",
    "animate.css": "^4.1.1",
    "axios": "^0.21.1",
    "bootstrap": "^4.6.0",
    "braces": "^2.3.1",
    "brunch": "^3.0.0",
    "crypto-js": "^4.0.0",
    "dotenv": "^8.2.0",
    "howler": "^2.2.0",
    "json": "^11.0.0",
    "kill-port-process": "^2.3.0",
    "prerender-node": "^3.2.5",
    "process-env-brunch": "^1.4.6",
    "prop-types": "^15.8.1",
    "react": "^16.13.1",
    "react-async-script-loader": "^0.3.0",
    "react-bootstrap": "^1.4.3",
    "react-device-detect": "^1.17.0",
    "react-dom": "^16.14.0",
    "react-ga": "^3.3.0",
    "react-google-invisible-recaptcha": "^0.2.11",
    "react-google-login": "^5.2.2",
    "react-helmet": "^6.1.0",
    "react-i18next": "^9.0.10",
    "react-intl": "^5.12.1",
    "react-modal": "^3.12.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "^4.0.0",
    "react-share": "^4.4.0",
    "react-tooltip": "^4.2.13",
    "sass-brunch": "^3.0.0",
    "socket.io": "^3.1.1",
    "ssri": "^8.0.1",
    "use-strict": "^1.0.1",
    "websocket": "^1.0.31"
  },
  "devDependencies": {
    "@babel/core": "^7.12.13",
    "@babel/plugin-transform-runtime": "^7.12.15",
    "@babel/plugin-transform-strict-mode": "^7.12.13",
    "@babel/preset-env": "^7.12.13",
    "@babel/preset-react": "^7.12.13",
    "@babel/register": "^7.12.13",
    "@babel/runtime-corejs2": "^7.12.13",
    "auto-reload-brunch": "^2.7.1",
    "babel-brunch": "^7.0.1",
    "babel-jest": "^26.6.3",
    "babel-preset-latest": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "clean-css-brunch": "^3.0.0",
    "esm": "^3.2.25",
    "express": "^4.17.1",
    "fingerprint-brunch": "^2.0.7",
    "fs": "0.0.1-security",
    "npm-force-resolutions": "0.0.3",
    "react-addons-test-utils": "^15.6.2",
    "react-notifications-component": "^3.0.3",
    "riteway": "^6.2.1",
    "uglify-es-brunch": "^1.0.5"
  },
  "main": ".eslintrc.js",
  "repository": {
    "type": "git",
    "url": "git+https://[email protected]/ImmersoTech/immerso-experience.git"
  },
  "license": "ISC"
}

NPM version 7.19.1
Node version 16.5.0

Note: I am using a deprecated library called react-aframe which may or may not affect it. I imagine it might since it is so old. I have tried looking in github and stackoverflow for similar issues but could not find it

I ran this command

grep GetIntrinsic node_modules/aframe/dist/aframe-master.js

to see where GetIntrinsic is used and it is imported a couple of times with require(). From looking at the function itself it seems to just get a value based off of a key from the INTRINSINCS object.

Javascript smooth scroll retain hash

I’m doing a smooth scroll on my page. But the problem is the hash link is removed when I smooth scroll directly to its target section. I need to keep the hash when smooth scrolling to the page. Does anybody know how to do this?

Here is my code

$('a[href*="#"]')
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {

    if (
      location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') 
      && 
      location.hostname == this.hostname
    ) {

      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
 
      if (target.length) {

        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top 
        }, 1000, function() {
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { 
            return false;
          } else {
            $target.attr('tabindex','-1'); 
            $target.focus();
          };
        });
      }
    }
  });


  
  
<div class="btn-container">  
<ul>
    <li class="tab-btn"><a class="smoothScroll" href="#stay">Stay</a></li>
    |
    <li class="tab-btn"><a class="smoothScroll" href="#travel">Travel</a></li>
    |
    <li class="tab-btn"><a class="smoothScroll" href="#promo">Promo</a></li>
</ul>
</div>

<div class="content-wrap" id="stay">
   <p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
</div>

<div class="content-wrap" id="travel">
<p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
 </div>

 <div class="content-wrap" id="promo">
<p> Lorem, ipsum dolor sit amet consectetur adipisicing elit. Amet accusantium nam aliquam temporibus perspiciatis reiciendis mollitia magni, soluta commodi debitis, culpa porro quibusdam iure harum totam. Itaque, reiciendis. Nisi, fugiat. </p>
 </div>

draggable d3 world globe in svelte

I have the next problem I’m trying to create a draggable world globe with d3 in a svelte app, the problem that i have is when a try to drag the globe the drag action is laggy I think that my problem have someting to do with a memory leak in the draggable component I don’t know if this is the main reason of this laggy behaviour. The globe was drew with svg’s

This is the App link:
https://codesandbox.io/s/cocky-benz-2mk5bs

Draggable component

<script>
    import { onMount, onDestroy, afterUpdate } from 'svelte';

    import { mouseAdjusted } from '../lib/Utilities';

    onMount(() => console.log('mounted'));

    afterUpdate(() => {
        //console.log('Destroyed');
    });

    export let mouseX;
    export let mouseY;
    let offset;

    let isMove = false;
    const start = (e) => {
        isMove = true;
        const element = e.target;
        const target = e.target.parentElement.parentElement.getScreenCTM();

        // get the mouse position in the svg shape
        offset = mouseAdjusted(e.clientX, e.clientY, target);
        // rest the shape mouse posicion from the shape x y coordinates
        offset[1] -= +element.getAttributeNS(null, 'y');
        offset[0] -= +element.getAttributeNS(null, 'x');
    };
    const move = (e) => {
        if (isMove) {
            const target = e.target.parentElement.parentElement.getScreenCTM();
            const [x, y] = mouseAdjusted(e.clientX, e.clientY, target);
            mouseX = offset[0] - x;
            mouseY = offset[1] - y;
        }
    };
    const end = () => {
        isMove = false;
        offset = null;
    };
</script>

<svelte:window
    on:mousemove|preventDefault|stopPropagation={move}
    on:mouseup|preventDefault|stopPropagation={end}
/>
<g class="draggable" on:mousedown|preventDefault|stopPropagation={start}>
    <slot />
</g>

Graph component

<script>
    import { onMount, onDestroy } from "svelte";
    import * as d3 from "d3";
    import * as topojson from "topojson-client";
    import Draggable from "./draggable.svelte";

    let width = 500;
    $: width = width * 0.95;
    let height = 500;
    $: height = height * 0.98;
    let world;
    let x;
    let y;
    let projection;
    let path;
    let ROTATION = [-45, -65, 0];
    // Add topojsom
    onMount(async () => {
      const resp = await d3.json(
        "/src/assets/world-administrative-boundaries.json"
      );
      world = await topojson.feature(resp, "world-administrative-boundaries");
    });

    $: ROTATION = [-x, y, 0];
    $: projection = d3
      .geoOrthographic()
      .fitSize([width, height], world)
      .scale([width / 3])
      .rotate(ROTATION);

    $: path = d3.geoPath(projection);

    const fillScale = d3
      .scaleOrdinal()
      .domain(["", ""])
      .range([" hsl(40, 98%, 47%)", "hsl(9, 64%, 50%)"])
      .unknown("hsl(227, 16%, 42%)");
    const strokeScale = d3
      .scaleOrdinal()
      .domain(["", ""])
      .range([" hsl(40, 98%, 35%)", "hsl(9, 64%, 35%)"])
      .unknown("hsl(227, 16%, 22%)");
    // transform to features
    $: countries = world?.features.map(obj => {
      const { geometry, properties, _ } = obj;
      //const d = path(geometry);
      const fill = fillScale(properties.iso3);
      const stroke = strokeScale(properties.iso3);
      const newProperties = Object.assign({ ...properties }, { fill, stroke });
      return Object.assign({}, { geometry, properties: newProperties });
    });

    //  $: console.log('features', features);
    //$: console.log('first', ROTATION);
</script>

<svelte:window bind:innerWidth={width} bind:innerHeight={height} />

<svg {width} {height}>
    <Draggable bind:mouseX={x} bind:mouseY={y}>
        {#if countries}
            <path class="sphere" d={path({ type: 'Sphere' })} />
            <g class="countries">
                {#each countries as country}
                    <path
                        d={path(country.geometry)}
                        fill={country.properties.fill}
                        stroke={country.properties.stroke}
                        
                    />
                {/each}
            </g>
        {/if}
    </Draggable>
</svg>

<!-- markup (zero or more items) goes here -->
<style>
    svg {
      border: 1px solid tomato;
    }

    .sphere {
      fill: var(--base-color-2);
    }
</style>

Transferring 2d array to php and get a return from php to html

I have a problem transferring a 2d-array to php and returning it back to html.

Here’s the array

var final_result_array = [['5','1646159576273','Australia','Male','ABC',1,'Overall'],
['8','1646159576273','Australia','Male','ABC',5,'Overall']]

Here’s the current ajax/jquery that I’m using

var jsonString = JSON.stringify(final_result_array);

///upload results
$.ajax({
    type: "POST",
    url: "data_upload.php",
    data: {data : jsonString}, 
    cache: false,

    success: function(json){
        alert(json.msg);
    }
});

Here’s the php

<?php

$msg = json_decode(stripslashes($_POST['data']));

echo json_encode($msg);
?> 

But somehow it’s not able to return $msg in the html. The ajax and php code are taken from somewhere here, and adapted accordingly.

There are some other things to be done in the php, but I have deliberately omit it out to make this question relevant.

Keep getting uncaught type error: cannot read properties of undefined (reading ‘style’) error is JS

Trying to switch from a Login form and a Register form. Keep getting error from Javascript:
uncaught type error: cannot read properties of undefined (reading ‘style’)

Not sure what else to look at according to this error. Have tried JS as a .js file, same issue.

Code:

enter code here


<div class="col-2">
                <div class="form-container">
                    <div class="form-btn">
                        <span onclick="login()"> Login </span>
                        <span onclick="register()">Register</span>
                        <hr id="Indicator">
                    </div>



                     <form id="LoginForm">
                        <input type="text" placeholder="Username">
                        <input type="password" placeholder="Password">
                        <button type="submit" class="btn">Login</button>
                        <a href="">Forgot Password</a>
                    </form>

                    <form id="RegForm">
                        <input type="text" placeholder="Username">
                        <input type="email" placeholder="Email">
                        <input type="password" placeholder="Password">
                        <button type="submit" `enter code 
           class="btn">Register</button>
                    </form>



enter code here

Javascript:
 <script>
 var LoginForm = document.getElementbyID("LoginForm");
 var RegForm = document.getElementbyID("RegForm");
 var Indicator = document.getElementById("Indicator");

   function register(){

     LoginForm.style.transform = "translateX(0px)";
     RegForm.style.transform = "translateX(0px)";
     Indicator.style.transform = "translateX(100px)";
    
}

   function login(){

     LoginForm.style.transform = "translateX(300px)";
     RegForm.style.transform = "translateX(300px)";
     Indicator.style.transform = "translateX(0px)";``
    
}

How do I configure localStorage for enabling dark mode?

I have a bare bones Astro project where I am using vanilla HTML, CSS, and JS. I am trying to enable the ability to toggle dark mode. I have a global.css file with root styles:

* {
  box-sizing: border-box;
  margin: 0;
}

:root {
  --primary: white;
  --text: black;
}

.darkmode {
  --primary: black;
  --text: white;
}

I then have a button component:

<button class="darkmode-toggle" aria-pressed="false">Enable Dark Mode</button>

<script>
  let darkmode = localStorage.getItem('darkmode');
  const systemPrefs = window.matchMedia('(prefers-color-scheme: dark)').matches;
  const darkmodeToggle = document.querySelector('.darkmode-toggle');

  const enableDarkmode = () => {
    document.documentElement.classList.add('darkmode');
    darkmodeToggle.textContent = 'Disable Dark Mode';
    darkmodeToggle.setAttribute('aria-pressed', 'true');

    localStorage.setItem('darkmode', 'enabled')
  }

  const disableDarkmode = () => {
    document.documentElement.classList.remove('darkmode')
    darkmodeToggle.textContent = 'Enable Dark Mode'
    darkmodeToggle.setAttribute('aria-pressed', 'false')

    localStorage.setItem('darkmode', null)
  }

  if (darkmode === 'enabled' || systemPrefs) enableDarkmode()

  darkmodeToggle.addEventListener('click', _ => {
    darkmode = localStorage.getItem('darkmode')

    darkmode !== 'enabled'
      ? enableDarkmode()
      : disableDarkmode()
  })
</script>

This implementation works which you will be able to see from this CodeSandbox. This issue I’m having is that when the page refreshes, the color goes back to the default.

I’m assuming this is usually fixed by using localStorage, which I am, making me think there’s something off about my implementation. Where am I misusing localStorage?

Avoid duplicate pair of json array

I am making a matchmaking system. My target is to avoid the multiple fights of my entries. As we can see on the result of my snippet. We can see that player 1 and player 2 got matched for the first time. After that, player 1 got matched again with player 2 for the second time. My target is to add another if statement to avoid the multiple entry. Any help will be appreciated. Thank you

const source = [
  {
    entryID: 1,
    entryName: "player1",
    weight: 1900,
  },
  {
    entryID: 2,
    entryName: "player1",
    weight: 1900,
  },
  {
    entryID: 3,
    entryName: "player2",
    weight: 1900,
  },
  {
    entryID: 4,
    entryName: "player2",
    weight: 1900,
  },



];

function combine(
  data = [],
  different = 0,
  maxGroupSize = 2,
  sortedStatement = (a, b) => a.weight - b.weight
) {
  const sortedData = [...data].sort(sortedStatement); 

  const dataGroups = sortedData.reduce((acc, item) => {
    const findedAccItem = acc.find(
      (accItem) =>
        accItem.length < maxGroupSize && 
        accItem[0].weight + different >= item.weight && 
        !accItem.find((obj) => obj.entryName === item.entryName ) 
    );
    if (findedAccItem) {
      findedAccItem.push(item);
    } else {
      acc.push([item]);
    }
    return acc;
  }, []);

  const namedDataGroups = dataGroups.reduce((acc, item, index) => {

    const key = [index, ...item.map((item) => item.weight)].join("_");
    acc[key] = item;
    return acc;
  }, {});

  return namedDataGroups;
}


console.log(combine(source));

This is the result of my snippet above:

{
  0_1900_1900: [{
  entryID: 1,
  entryName: "player1",
  weight: 1900
}, {
  entryID: 3,
  entryName: "player2",
  weight: 1900
}],
  1_1900_1900: [{   // player 1 and player 2 got matched again. I need to avoid multiple fight
  entryID: 2,
  entryName: "player1",
  weight: 1900
}, {
  entryID: 4,
  entryName: "player2",
  weight: 1900
}]
}

This is my target result: (

{
    0_1900_1900: [{
    entryID: 1,
    entryName: "player1",
    weight: 1900
  }, {
    entryID: 3,
    entryName: "player2",
    weight: 1900
  }],
    1_1900: [{
    entryID: 2,
    entryName: "player1",
    weight: 1900
  }],
    2_1900: [{
    entryID: 4,
    entryName: "player2",
    weight: 2000
  }]
  }