Function does not return value when use promise, JavaScript

I have a very few knowledge in JavaScript, so sorry in advance for this question.

I have a method:

function userAgent() {
            var result = "";

            navigator.userAgentData.getHighEntropyValues(["platformVersion"])
                .then(ua => {
                    if (navigator.userAgentData.platform === "Windows") {
                        const majorPlatformVersion = parseInt(ua.platformVersion.split('.')[0]);
                        if (majorPlatformVersion >= 13) {
                            console.log("Windows 11 or later");
                            result = "Windows 11 or later";
                        }
                        else if (majorPlatformVersion > 0) {
                            console.log("Windows 10");
                            result = "Windows 10";
                        }
                        else {
                            console.log("Before Windows 10");
                            result = "Before Windows 10";
                        }
                    }
                    else {
                        console.log("Not running on Windows");
                        result = "Not running on Windows";
                    }

                    
                });

            return result;
        }

And it returns empty string, but prints to console the correct value.

Please, tell me what is my mistake and how to return value here, I want to use it after.

Thank you!

What does this symbol means in javscript >>>= [duplicate]

I was going through a program solution “Finding Binary Gap” on different sites and I came across a symbol that I’ve never scene before in Javascript i.e ‘>>>=’.

I tried to understand but counldn’t.

  for(var curr=0; n !== 0; n>>>=1) { 
  if(n % 2 === 0) { 
      curr++; 
  } else { 
      curr = 0; 
  } 
  maxZeros = Math.max(maxZeros, curr);
} 

This was the code snippet.
Any idea, comment or reply is appreciated. Thank you.

writing program in function not executing the CLI command in nodeJs

I am making a custom CLI so I wrote a code

#!/usr/bin/env node

var { program } = require("commander");
var { prompt } = require("inquirer");
const Science = require("./Science");
program.version("0.0.1");

// questions
const questions = [
  {
    type: "list",
    name: "subjectType",
    message: " Select export Source ",
    default: false,
    choices: [
      "Science",
      "Maths",
      "English",
      "Exit",
    ],
  },
];

function startQuery() {
  program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });
}

function wantToExit() {
  inquirer
    .prompt([
      {
        name: "moreQuery",
        type: "confirm",
        message: "Want to do anything else?",
      },
    ])
    .then((answer) => {
      if (answer.moreQuery) return startQuery();
    });
}

program.parse(process.argv);

so when I type Subject run in console it won’t run my cli but when I remove startQuery function its execute the Program and I Don’t know why its behaving like this

running by removing function startQuery()

program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });

Then in console I write Subject run its Execute properly
but if I do this its not executing the program

function startQuery() {
  program
    .command("run")
    .alias("r")
    .description("Subject")
    .action(() => {
      prompt(questions).then((answers) => {
        if (answers.subjectType === "Science") {
          Science();
        } else if (answers.subjectType === "Maths") {
          // Maths();
        } else if (answers.subjectType === "Exit") {
          wantToExit();
        }
      });
    });
}

As i need this startQuery function in wantToExit function so I can use it again if user want to continue

Disabled Move a dragdrop element when scrolling wheel

I try that when I do MOUSE WHEEL the dragdrop continues to work, in jQuery it works but if I want to make it native in javascript it does not work, has someone happened this? I try to put this event but I can not solve it …

DOES NOT FIX THE PROBLEM

document.addEventListener(“mousewheel”, function( event ){
event.preventDefault();
}, false);

var dragged;

document.addEventListener("drag", function( event ){
    //console.log("A");
}, false);

document.addEventListener("dragstart", function( event ){
        dragged = event.target;
    //console.log("B");
    event.target.style.opacity = .5;
}, false);


document.addEventListener("dragend", function( event ){
    
    event.target.style.opacity = "";
  //console.log("C");
}, false);

document.addEventListener("dragover", function( event ){
    event.preventDefault();
  //console.log("D");
}, false);

document.addEventListener("dragenter", function( event ){
    if( event.target.className == 'dropzone' ){
    console.log("E");
    event.target.style.background = "red";
  }
}, false);

document.addEventListener("dragleave", function( event ){
    if( event.target.className == 'dropzone' ){
    console.log("F");
    event.target.style.background = "";
  }
}, false);


document.addEventListener("drop", function( event ){
    event.preventDefault();
  if( event.target.className == "dropzone" ){
    //console.log("G");
    event.target.style.background = "";
    dragged.parentNode.removeChild(dragged);
    event.target.appendChild( dragged );
  }
}, false); 


// DOES NOT FIX THE PROBLEM
document.addEventListener("mousewheel", function( event ){
    event.preventDefault();
}, false);
<div class="dropzone">
  <div class="draggable"
   draggable="true" 
   ondragstart="event.dataTransfer.setData('text/plain',null)">
     Hi!.!
  </div>
</div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<div class="dropzone"></div>
<style>
.dropzone{
  width: 200px;
  min-height: 25px;
  margin-bottom: 300px;
  background-color: violet;
  border: 1px solid #9457EB;
  padding: 5px;
  transition: 1000m easy all;
}
.draggable{
  background-color: white;
  padding: 3px;
  text-align: center;
  transition: 400ms ease all;
}
.draggable:hover{
    background-color: yellow;
 }
</style>

DEMO

What can be used to identify the source collection for common elements from n-number of collections (Node.js nd JavaScript)?

Given n-number of collections/arrays, I would like to identify common elements and which collections they are common to.

This is a little bit similar to this question, however there could be similar elements in say, colletion1 and collection3, or even all of them. I am not only looking for elements similar in all collections. In addition I am open to using any Node.js libraries.

var arr["One"] =   arrProps[{name: '1', prop2: 'aaa'}], arrValues['apple', 'orange', 'banana', 'pear', 'fish', 'pancake', 'taco', 'pizza'];
var arr["Two"] =   arrProps[{name: '2', prop2: 'bbb'}], arrValues['taco', 'fish', 'apple', 'pizza', 'car'];
var arr["Three"] = arrProps[{name: '3', prop2: 'ccc'}], arrValues['banana', 'pizza', 'fish', 'apple', 'orange', ];
var arr["Four"] =  arrProps[{name: '4', prop2: 'ddd'}], arrValues['grape', 'pear', 'chicken', 'car', 'orange'];

Result should be:

[arrValue, arrProps.name]
apple: 1,2,3
banana: 1,3
pear: 1,4
fish: 1,2,3
taco:  1,2
pizza: 1,3
car: 2,4
orange: 3,4

Rather than using arrays, if this were represented as a JSON graph, would that be any easier to solve, and if so, how?

Tradingview Lightweight candlestick charts price depth

I’m building a candlestick chart with preset of price data. By default it is set to two decimals 0.01 of price. However my price data ranges way past from 0.01 to 0.0000002 etc. I was searching docs for property to customize default value of two deciamals to lesser range of numbers. In the docs it says: “The minimum possible step size for price value movement. This value shouldn’t have more decimal digits than the precision”. Thank you

Here’s my code and chart data



const log = console.log;

const chartProperties = {
    width:1200,
    height:600,
    timeScale:{
        timeVisible:true,
        secondsVisible:false,
    }
}

const domElement = document.getElementById('chart');
const chart = LightweightCharts.createChart(domElement,chartProperties);
const candleSeries = chart.addCandlestickSeries();

fetch(`http://localhost:8888/trade/tok-btc/chart/dataset.txt`)
    .then(res => res.json())
    .then(data => {
        const cdata = data.map(d => {
            return {time:d[0]/1000,open:parseFloat(d[1]),high:parseFloat(d[2]),low:parseFloat(d[3]),close:parseFloat(d[4])}
        });
        candleSeries.setData(cdata);
    })
    .catch(err => log(err));
[
[1640060100000,"0.004","0.008","0.002","0.0055",1640060159999],[1640060160000,"0.0055","0.008","0.002","0.005",1640060219999],[1640078220000,"0.005","0.008","0.002","0.0045",1640078279000],[1640078280000,"0.0045","0.0065","0.0043","0.0058",1640078339000]
]

How to replace “TRUE” with a checked checkbox and “FALSE” with a nonchecked checkbox in an HTML table?

I have a table that is formatted as

<table id="daily">

        <thead>
            <tr>
                <th class="year">year</th>
                <th class="cutoff">cut off date</th>
                <th class="name">Stefan</th>
                <th></th>
                <th class="name">Johnny</th>
                <th></th>
                <th class="name">Effie</th>
                <th></th>
                <th class="name">Karol</th>
                <th></th>
                <th class="name">Vardan</th>
                <th></th>
                <th class="name">Aman</th>
                <th></th>
                <th class="name">Jaspal</th>
                <th></th>
                <th class="name">Laurent</th>
                <th></th>
            </tr>
        </thead>
        <tbody data-sheetdb-url="https://sheetdb.io/api/v1/xxxxxxxxx?sheet=Dashboard" data-sheetdb-sort-by="age"
            data-sheetdb-sort-order="desc">
            <tr>
                <td id="date">{{year}}</td>
                <td class="cutoff"><i>{{cut off date}}</i></td>
                <td id="hours">{{Stefan}}</td>
                <td class="checkbox">{{c1}}</th>
                <td id="total">{{Johnny}}</td>
                <td class="checkbox">{{c2}}</th>
                <td id="total">{{Effie}}</td>
                <td class="checkbox">{{c3}}</th>
                <td id="total">{{Karol}}</td>
                <td class="checkbox">{{c4}}</th>
                <td id="total">{{Vardan}}</td>
                <td class="checkbox">{{c5}}</th>
                <td id="total">{{Aman}}</td>
                <td class="checkbox">{{c6}}</th>
                <td id="total">{{Jaspal}}</td>
                <td class="checkbox">{{c7}}</th>
                <td id="total">{{Laurent}}</td>
                <td class="checkbox">{{c8}}</th>
            </tr>
        </tbody>
    </table>

The CSS I have is

#daily {
display: block;
position: relative;
background-color: #3C4AB8;
color: white;
border-collapse: collapse;
overflow-x: auto;
overflow-y: auto;
max-height: 80vh;
width: 90vw;
border: 10px solid #222A68;
font-family: 'Roboto Mono', monospace;
font-size: 20px;
margin-top: 2em;
margin-bottom: 2em;
}


#table thead th {
    position: sticky;
    top: 0;
}

td,
th {
    border: solid #E3DAFF 2px;
    padding: 0.5rem;
}

th {
    position: sticky;
    top: 0;
    border-top: none;
    background: #222A68;
    top: 0;
    text-align: center;
    padding: 8px;
    text-transform: uppercase;
}

td {
    border-bottom: none;
    white-space: wrap;
}

And so on.

This table fetches some data from a Google Sheet using https://sheetdb.io/ as a backend. There are values in some cells that are checkboxes returning as either “TRUE” or “FALSE”.

How can I replace these values with checkboxes that are checked when the value is “TRUE” and unchecked when the value is “FALSE”?

Thank you!

reactjs: a context component function not updating its variable; usestate not working immediately?

I’m working on auth in my app, so I created a context to manage it:

import React, { useState } from "react";

const AuthContext = React.createContext({
    token: "",
    isLoggedIn: false,
    login: (token) => { },
    logout: () => { },
});

export const AuthContextProvider = (props) => {
    const [token, setToken] = useState(null);
    const [userIsLoggedIn, setUserLoggedIn] = useState(false)

    const loginHandler = async (token) => {
        setToken(token);
        setUserLoggedIn(true)
        console.log(userIsLoggedIn)   //prints false
    };

    const logoutHandler = () => {
        setToken(null);
        setUserLoggedIn(false)
    };

    const contextValue = {
        token: token,
        isLoggedIn: userIsLoggedIn,
        login: loginHandler,
        logout: logoutHandler,
    };


    return (
        <AuthContext.Provider value={contextValue}>
            {props.children}
        </AuthContext.Provider>
    );
};

export default AuthContext;

The problem is that when I call context.login(‘some token’) from an outside component and then console.log(context.isLoggedIn) I get false the first time, but if I call context.login(‘some token’) once again I get true. Every succesive time after that I get true now. It might have to do with the fact the “console.log(userIsLoggedIn)” inside the loginHandler says “false” (the first time the context.login is called) even though the setUserLoggedIn is right above it. I think the userIsLoggedIn variable is changed after the context is updated in the component it’s used in, but I don’t know how to fix that.
I will appreciate any help on this

Getting undefined during return in javascript function [duplicate]

So I have a function

const getErrorCached = (label) => {
  redisModel.getErrorLog(label,function(err,res){
    if(err)throw err;


    Promise.all(JSON.parse(res).map(doc => {return doc.ids}))
    .then(result => {
      console.log(result)
      return result})
    .catch(error => {
      return error
    })
})
}

And I am calling this in another function like this

const getTargets = (label) => (callback) => {
  const date = getDate();
  const condition = getConditions();
  const cachedErrorIds = getErrorCached(label)
  console.log("ids",cachedErrorIds);

  .
  .

Now weird thing is In console.log(result) I am getting result logged but when I am calling that in another console.log(“ids”,cachedErrorIds); its ggetting logged undefined,what is happening here

Uncaught ReferenceError: Cannot access ‘FETCH_MESSAGES’ before initialization

I am getting error, not during compilation, but in my browser,
I have attached the files here

message.js reducer file

import store from './index';

// ACTION TYPES
const FETCH_MESSAGES = "FETCH_MESSAGES";

// ACTIONS
export const fetchMessages = ( id ) => {
    console.log(store.getState());
    return {
        type: FETCH_MESSAGES,
        payload: id
    }
}

// REDUCERS
export default function reducer( state = -1, action ) {
    switch(action.type) {
        case FETCH_MESSAGES :
            return action.payload;
        default:
            return state;
    }
}

index.js

import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import chatReducer from './chat';
import messageReducer from './messages';
const reducer = combineReducers({
    chatStore : chatReducer,
    messageStore : messageReducer,
});
const store = createStore(reducer, applyMiddleware(thunk));
export default store;

Error Message
Scrrenshot of error message

I am trying to add add Search filter in react but I am getting this error

  1. I am trying to add Seach filter using the react, and using json data
    I am trying to match it with the search term

  2. Below is my code

    const App = () => {
    const [searchTerm, setSearchTerm] = useState([“”])
    const [query, setQuery] = useState(“”);

    useEffect(() => {
    const url = “https://60d075407de0b20017108b89.mockapi.io/api/v1/animals”;

    const fetchData = async () =>
      {
              try
          {
              const response = await fetch(url);
              const json = await response.json();
              console.log([json].query);
              setQuery(json.query);
          }
              catch (error)
          {
              console.log("error", error);
          }
      };
      fetchData();
    

    }, []);

    return (

    <input type=’text’ placeholder=’search….’ onChange={event => { setSearchTerm(event.target.value) }} />

      {
    
              query.filter((val) => {
                if (searchTerm === "s")
          {
              return val
          }
              else if (val.name.toLowerCase().includes(searchTerm.toLowerCase())) {
              return val
          }
          else
              return false
          }).map((val) =>
          {
              return (
              <div className='user' >
              <p>{val.name}</p>
              <p>age: {monthDiff(val.bornAt)} months</p>
    
            </div>
          );
          })}
    </div>
    

    );
    };

When I try to execute, I am getting this below error
can anyone explain why it is happening

> Uncaught TypeError: Cannot read properties of undefined (reading
> 'toLowerCase')

Best way to add eCommerce solution to a wordpress website and tools I can use to add custom business card designing [closed]

I have build a website for a printing business using wordpress with basic pages like About us, Contact and Services Information. Now the owner wants to add features something similar to VistaPrint (Not all only some) like to be able for users to Design their own Business Cards and then Order it using an eCommerce Store.
I know a bit of javascript and React but not that much experienced.I am looking for some good suggestions on two things

  • Either I use Node js and React to build such a solution (Ofcourse i still have to learn more) and then figure out how to integrate React application with existing wordpress website
  • OR I need some ideas on Plugins to use on wordpress to do this (I don’t want to go this way as i want to experience React)

If someone has done something similar please share your experience . Rebuilding the entire website is not an option as its not cost effective.