Sorting object array by a property value

I have this array ob objects that I need to sort by their number

var products = [
{
 name: 'Gift Box',
 productNumber: '44',
 SKU: 'ABCD'
},
{
 name: 'Tabletop Game',
 productNumber: '63',
 SKU: 'DEFG'
},
{
 name: 'Poker Deck',
 productNumber: '25s',
 SKU: 'HIJK'
},
{
 name: 'Box of chocolates',
 productNumber: '96p',
 SKU: 'LMNO'
},
{
 name: 'Box of Swiss chocolates',
 productNumber: '96s',
 SKU: 'PQRS'
},
{
 name: 'Gift card',
 productNumber: '81',
 SKU: 'TUVW'
}];

As you can see, some of the productNumber properties have a letter in them, and as such, I think is not going to be as easy as just doing a products.sort((a, b) => parseInt(b.productNumber) - parseInt(a.productNumber));, so, how can I solve this?

Jest – Test Suite Failed to Run “x.default is not a constructor”

Two of my jest test suites are failing to run, I receive the errors “_player.default is not a constructor” and “_gameboard.default is not a constructor”.

I have a player class that I want to test:

export default class Player {
 constructor(name) {
  this.name = name;
  this.isTurn = false;
  this.isConsideringAttack = false;
  this.gameboard = new Gameboard();
  }
 }

And a gameboard class:

export default class Gameboard {
 constructor() {
  this.board = [];
  this.initialiseBoard();
  }
 }

The error I receive when I try to run the player test suite:

  ● Test suite failed to run

TypeError: _player.default is not a constructor

  3 |
  4 | const players = {
> 5 |   user: new Player('user'),
    |         ^
  6 |   computer: new Player('computer'),
  7 | };
  8 |

  at Object.<anonymous> (src/game.js:5:9)
  at Object.<anonymous> (src/dragAndDrop.js:2:1)

The error I receive when I try to run the gameboard test suite:

  ● Test suite failed to run

TypeError: _gameboard.default is not a constructor

   7 |     this.isTurn = false;
   8 |     this.isConsideringAttack = false;
>  9 |     this.gameboard = new Gameboard();
     |                      ^
  10 |   }
  11 |
  12 |   attack(x, y, gameboard) {

  at new Player (src/factories/player.js:9:22)
  at Object.<anonymous> (src/game.js:5:9)
  at Object.<anonymous> (src/dragAndDrop.js:2:1)

I’m very new to Jest, I couldn’t find a fix for this despite spending a few hours searching. Any help would be appreciated.

Use mouseover to add animation on hover

I’m trying to add an animation to an element when someone hover on it.

My thought is to add a class with keyframes that attach to the element by adding a mouseover event listener to it.

The reason I don’t use CSS is because I want the animation to be finished even the mouse leave the element before the animation is finished. For example, the mouse is moved out of element when rotating on 180 degree (full animation is 360 degree)

But sadly it’s not working and I don’t know why…

const item = document.querySelector('#rotate');

item.addEventListener('mouseover' function(e) {
  if(item) e.classList.add('rotate');
});
#div {
  width: 120px;
  height: 120px;
  background-color: orange;
}

.rotate {
  animation: rotating 1s ease 0s 1 normal forwards;
}

@keyframes rotating {
  0% {
    transform: rotate(0);
  }

  100% {
    transform: rotate(360deg);
  }
}
<div id='rotate'></div>

How to call HTML attribute ‘minlength’ in JavaSript

I have this code snippet:

<div>
      <label for="requiredSize">Required Size 5 : </label>
      <input type="text" name="requiredSize" id="requiredSize" class="required_size" minlength="5" />
</div>

I am doing a form validation exercise, and I need to have one of the requirements be based on required size. How can I call the minlength into my Javascript file to be used since it does change throughout the form.

I have tried documnet.querySelector("minlength") to try and save it as a variable, but it wasn’t being recognized.

How can i use createPortal in NextJS when using typescript?

I’m using Nextjs + Typescript to make a toy project
and I’m having a problem when using createPortal to create a Modal.
I got a problem with render in Browser.
why doesn’t it work?
I have done a lot of trying googling but i couldn’t solve it.
Plz help me.

enter image description here

HOC/Portal.tsx

import { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";

interface Props {
  children: any;
}
const Portal: React.FC<Props> = ({ children }) => {
  const ref = useRef<HTMLDivElement | null>(null);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    ref.current = document.querySelector("overlay-root");
    setMounted(true);
    return () => setMounted(false);
  }, []);

  return mounted ? createPortal(children, ref.current!) : null;
};

export default Portal;

src/Components/layout/Header.tsx

...
 {isLoginModal && (
            <Portal>
              <Login
                onChangeLoginModal={onChangeLoginModal}
                onChangeLoginState={onChangeLoginState}
                isLoginState={isLoginState}
                isLoginModal
              />
            </Portal>
          )}
...

pages/_documents.tsx

 ...
  render() {
    return (
      <Html>
        <Head>
          <meta charSet="utf-8" />
          <meta
            name="viewport"
            content="target-densitydpi=device-dpi, user-scalable=0, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, width=device-width"
          ></meta>
          <link
            href="https://fonts.googleapis.com/css2?family=Dongle&family=Noto+Sans+KR:wght@500&family=Roboto:wght@500&display=swap"
            rel="stylesheet"
          />
        </Head>
        <body>
          <Main />
          {/* here */}
          <div id="overlay-root"></div>
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

ordering sorting based multiple values

I have a list of objects where the object has the below variables.

BO={Name: String, Position: Number, SortOrder: Number};

Here SortOrder is just a number starting with 1 and increments by one for subsequent objects in an ascending order.
The name and position values are provided and sort order needs to be populated.
These are the rules to sort the list:

1.Sort the list based on the value of position
2.If the two objects have same position value then we need to sort the objects based on the Name in an alphanumeric order

I can use simple sorting based on the value of position
by using a loop and using the below logic, but I need to be able to sort based on Name if the two positions have the same value.

for(i=0;i<Arr.length;i++)
    {
      for(j=i+1;j<Arr.length;j++)
        {
          if(Arr[i].poition>Arr[j].position)
            {
              temp=Arr[j];
              Arr[j]=Arr[i];
              Arr[i]=temp;
        }
      }
    }

let me know how this can be achieved
e.g.1
given :
[{Name:A,Position:2}
,{Name:B,Position:1},
{Name:C,Position:3}
]

Out put:
[{Name:B,Position:1,SortOrder:1},
{Name:A,Position:1,SortOrder:2},
{Name:C,Position:3,SortOrder:3}]


e.g.2
given
[
{Name:Ab,Position:2},
{Name:A,Position:2},
{Name:HI,Position:4},
{Name:C,Position:3}
]
Out put:
[{Name:A,Position:2,SortOrder:1}
,
{Name:Ab,Position:2,SortOrder:2}
,
{Name:C,Position:3,SortOrder:3},
{Name:HI,Position:4,SortOrder:4}]

I am thinking of using a for loop and javascript to implement this. Thank You.

does the javascript remove really removed the element

I have a popup window and I am setting the window hidden in css like this when initial the window:

#popper-container1 {
  width: 250px;
  max-width: 100%;
  position: absolute;
  left: 0;
  top: 0;
  touch-action: none;
  transition: opacity 0.2s;
  background-color: #f5f8fa;
  visibility: hidden;
}

after click some button, show this window using js code like this:

export async function showTranslateResultPanel(translation: string) {
  let translateBtn = document.getElementById("popper-container1");
  if (translateBtn) {
    translateBtn.style.visibility = "visible";
    translateBtn.style.zIndex = "999999999";
    translateBtn.style.position = "absolute";
    let xAxios = await LocalStorage.readLocalStorage("pop-window-x-axios");
    let yAxios = await LocalStorage.readLocalStorage("pop-window-y-axios");
    translateBtn.style.transform = "translate(" + (xAxios) + "px," + (yAxios) + "px)";
    setTransResult(translation);
  }
}

When the user close the popup window, I am using this code the remove the elment:

export function closePopupWindow() {
  let translateBtn = document.getElementById("reddwarf-translate-app");
  if (translateBtn) {
    translateBtn.remove();
  }
}

the reddwarf-translate-app was the parent element of popper-container1, when remove the parent element, the sub element also removed. But I am facing the problem is that when the next time initial the popup window, the window was showing by default, the hidden was override! why did this happen? what should I do to make it work? I check my code and logic and did not found any problem, why the hidden did not make effect when the sencond time open the popup window? does the remove function really delete the element? or did not remove the css?

Reset Stack Navigators is nested inside Drawer Navigator

First of all, I would like to present My Navigation State:

■ RootStack (Stack)
   ▪ MainDrawer (Drawer)
      ▪ ServicesNavigator (Stack)
      ▪ TurnTrackingNavigator (Stack)
      ▪ EmployeesNavigator (Stack)

in ServicesNavigator, I build the App with ServicesStack –> ServiceDetails Screen.
enter image description here

*I press the Services of MainDrawer it navigate ServicesStack, When my App to ServiceDetails Screen, I right away use the Drawer to go to another Stack (ex: EmployeesNavigator), and then I press the Services in Drawer to back ServicesScreen.
But it native Stack ServiceDetails (that Stack stored), what I need is ServicesStack.

I want to ask how can when I click Drawer it resets the stack or what way to resolve.

Randomly show max 3 blocks per page

I have several blocks in the form of circles.

I made it so that when you click on the block, it dissolves. But if you dissolve all the blocks, the page will remain empty.

How can I make it so that there are a maximum of 3 blocks on the page, which are selected randomly? Also, the page is never blank.

To select 3 random I use

var randomnumber = Math.floor(Math.random()*10) + 1;
var circle1 = $('#circle' + randomnumber);
var circle2 = $('#circle' + randomnumber);
var circle3 = $('#circle' + randomnumber);

But I can’t hide everything and still show 3 selected ones. In addition, when we clicked on one of them and it disappeared, a new one should appear in its place

I tried to style all blocks visibility: hidden; and in the script like this var circle1 = $('#circle' + randomnumber).css('visibility', 'visible'); but in the end nothing comes up.

$("div").click(function() {
  $(this).fadeOut("slow");
});

const nodes = document.querySelectorAll('.animation');
for(let i = 0; i < nodes.length; i++) {
  nodes[i].addEventListener('click', (event) => {
    event.target.style.animation = 'Animation 200ms linear';
    setTimeout(() => {
      event.target.style.animation = '';
    }, 220);  });
}
.circle1 {
  background: #456BD9;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle2 {
  background: #fb6df9;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle3 {
  background: #6de2fb;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle4 {
  background: #81fb6d;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle5 {
  background: #e9fb6d;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle6 {
  background: #6bfc90;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle7 {
  background: #a5950a;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle8 {
  background: #a50a74;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle9 {
  background: #ff0c00;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

.circle10 {
  background: #06aec2;
  clip-path: circle(50%);
  height: 50px;
  width: 50px;
  margin: 20px;
}

@keyframes Animation {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(.8);
  }
  100% {
    transform: scale(1);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="circle1 animation"></div>
<div class="circle2 animation"></div>
<div class="circle3 animation"></div>
<div class="circle4 animation"></div>
<div class="circle5 animation"></div>
<div class="circle6 animation"></div>
<div class="circle7 animation"></div>
<div class="circle8 animation"></div>
<div class="circle9 animation"></div>
<div class="circle10 animation"></div>

How to generate true randomness in JavaScript

How to generate true randomness in JavaScript

I’ve been wondering on this question for a little while now, and I don’t have like a reason to know this, I am just curious.

So we all know the Math.random() function in JavaScript. But this is not the answer, because I want to know how to generate a random number without this function, just pure randomness.

So, if you know an answer, please let me know.

Pass variable from function js to other function js

I’m trying to pass and hold the value of store so that everytime user selects a different day, the value of store remains the same.

store and day chart

At first, I managed to show the result when I chose the store and the day values. However, when I changed to a different day, it doesn’t hold the store value.

function changestore(){
      var filterstoregen = document.getElementById("filterstoregen").value;
      return filterstoregen;
      window.location.href='/new-retail/visitorreport?storename_='+filterstoregen;
 }


function changeday(){
      var storename2 = changestore();
      var filterday = document.getElementById("filterday").value;
      window.location.href='/new-retail/visitorreport?storename_='+storename2+'&dayname='+filterday;
 }

If I want to see the results of a different day, I need to choose again the store value first. This is because the chart becomes blank as if the store value is not selected.

Note that the functions written in the same file which is visitorreport.php.

Hopefully I have provided enough information to get some help. Thanks in advance.

Selenium with user interaction

I have a project in which selfie will automatically be clicked by detecting the face in the frame. There is no click button to take the selfie.
Now what i need to do is to automate the whole process using selenium(in python). So is there any way we can pass the data to that capture?

Or is there any other way i can achieve this?

How to store images in database?

I’m working on a platform using HTML, Javascript, SQL, Ajax and PHP.
The platform asks for a pictures and those pictures will have to be displayed later.
I’ve seen people saying that you shouldn’t store them in a database if they’re a lot, but just storing the path doesn’t seem like it would work because that would mean that the user could never change the pictures to another folder or delete them, right? And that wouldn’t work for what I want.
Does anyone have any suggestions on what I should do?

Javascript Array Foreach Callback Function With Recursion Push Values

I’ve been following this awesome solution. However for some reason on this block of code:

nodes.forEach(function(e){
    if(e.parent === currentNodeId){
        e = addChildrenToNode(e);
        node.children.push(e);
    }
});

The forEach callback function “e” param results to null instead of pushing the whole object into the node.children array. In order for me to get the actual values, I’ve manually set the values instead of using the “e” which will be the whole object e.g.:

node.children.push({ _id: e._id, name: e.name });

However, I’m not able to convert this line:

e = addChildrenToNode(e);

To do the recursion and append the children. I’m thinking that this is due to the old version of JS that we’re using on the server without the ES6 functionalities? Need your inputs. Thank you very much!