Typescript: formatting nested type in interface

I have interface CountersData that I would like to model off of my JSON data. As seen below, I have a nested id (in example below 1830 and 1835 are ids) property that is a array of a nested dictionaries, which I also want to be optional.

I have been unable to make it optional, so I am unable to fetch the proper data. How should this data be formatted? See below my code and the JSON format.

interface CountersData {
  //other properties

  //want this to be optional
  [id: number]: {
    count_targets: number;
    count_targets_excluded: number;
    count_targets_pending: number;
    count_targets_in_progress: number;
    count_targets_completed: number;
    count_targets_failed: number;
  }[];

  [key: string]: number | string | any | undefined;
}

enter image description here

How do I make ‘mouseleave’ event not trigger when hovering over datalist?

I have a sidebar on my page containing a form and some filters. The sidebar is initially collapsed and can be expanded when hovering over via a ‘mouseenter’ event, and will collapse when the mouse leaves the sidebar via a ‘mouseover’ event. This seems to work well, but I had an error when trying to add a input field in my form containing a datalist with a list of text options. The problem now is that when I hover over the options, the sidebar will trigger a ‘mouseleave’ event and collapse, even though the datalist/option elements are a child of the sidebar element. Is there a way to prevent the sidebar from collapsing or am I better off using select instead of datalist, since the select tag seems to not trigger ‘mouseleave’?

let sidebar = document.getElementById("sidebar");
sidebar.addEventListener("mouseenter", function(e) {
  toggleSidebar(e, BODY_CONTENT);
});
sidebar.addEventListener("mouseleave", function(e) {
  toggleSidebar(e, BODY_CONTENT);
});

function toggleSidebar(e, bodyContent) {
  if (e.type == "mouseenter") {
    e.target.style.width = e.target.dataset.expandWidth + "px";
    document.getElementById(bodyContent).style.marginLeft =
      e.target.dataset.expandWidth + "px";
  } else if (e.type == "mouseleave") {
    console.log(e);
    e.target.style.width = e.target.dataset.collapseWidth + "px";
    document.getElementById(bodyContent).style.marginLeft =
      parseInt(e.target.dataset.collapseWidth) + 10 + "px";
  }
}
<div class="sidebar" id="sidebar" data-collapse-width="50" data-expand-width="300" style="width: 50px;">
  <div id="flex-sidebar">
    <div class="sidebar-header">
      <h2>
        Filters
      </h2>
    </div>
    <form action="" method="POST" autocomplete="off">
      <div class="form-group">
        <label for="category-filter">Category:</label>
        <input class="form-control me-2" type="search" placeholder="Filter Category" name="category-filter" value="" list="test">
        <datalist class="sidebar-dropdown" id="test">
          <option value="Option 1">1</option>
          <option value="Option 2">2</option>
        </datalist>
      </div>
    </form>
  </div>
</div>

addon domain laravel sanctum

Maybe someone knows how to add a second domain?
APP_URL=http://api.domain.com

SANCTUM_STATEFUL_DOMAINS=domain.com

I need to add, for example, the seconddomain.com domain, but for the api to remain on api.domain.com and for the site to be accessible both on domain.com and seconddomain.com
I did like this SANCTUM_STATEFUL_DOMAINS=domain.com,seconddomain.com
If I look through domain.com everything is OK, but if through seconddomain.com, then after /login no request is made for user, tell me what could be the problem

How can a nested method access properties from another object in a class?

I am having trouble accessing the necessary object properties in a method. Here I have a simplified version of what I am trying to do. I have a Game class that is used to make a new game object. Once that object has been made I am trying to run the draw method. The draw method will use information from state.house.color, but I cannot seem to figure out how to access it since using “this” in draw will not refer to the game object. I have used .bind(this) in the past, but that doesn’t seem to be helping here as I would need to bind an object not a function. Thanks for any insight!

class Game {
    state = {
        house: {
            color: "blue"    
        }
    }
    assets = {
        house: {
            draw(){
                //some logic here such as console.log(this.state.house.color)
            }
        }
    }
};

let testGame = new Game();

testGame.assets.house.draw();

React loan calculator

I’m trying to make a loan calculator without factoring in the interest rate. But I messed up on the calculations as the pay back loan/month results in whatever number user puts. It’s not using the formulas.

*I used material UI for the forms.

Calculator example is here: https://i.stack.imgur.com/w6Um3.png

const Loancalculator = (props) => {
{
const [loan, setLoan] = useState(10000);
const [duration, setDuration] = useState(1);
const [dates, setDates] = useState([]);
const [inputs, setInputs] = useState({
    option: 0
})

const getPrincipal = (month) => {
  let dividedAmount = (loan / duration) * month;
  return Math.round((dividedAmount + Number.EPSILON) * 100) / 100;
};

const getTotalRepayment = (month) => {
   return (
     Math.round(
      (getInterest(month) + getPrincipal(month) + Number.EPSILON) * 100
    ) / 100
  );
};

useEffect(() => {
  let datesArray = [];

  for (let i = 1; i <= duration; i++) {
    let date = new Date();
    date = new Date(date.setMonth(date.getMonth() + 1 + i));
    datesArray.push({
      date: `${date.getDate()}/${
        date.getMonth() + 1
      }/${date.getFullYear()}`,
      month: i,
    });
  }

  setDates(datesArray);
}, [duration]);

  return (
  <FormControl sx={{ m: 1 }} size="small" className="amountContainer">
      <InputLabel htmlFor="standard-adornment-amount">Amount</InputLabel>
      <Input
      id="loan-input"
        value={loan}
        onChange={(e) => setLoan(e.target.value)}
        startAdornment={<InputAdornment position="start">$</InputAdornment>}
        label="Amount"
      />
    </FormControl>
     <Box sx={{ minWidth: 50 }} className="option2Container">
      <FormControl >
    <InputLabel variant="standard" htmlFor="uncontrolled-native">
    </InputLabel>
     <NativeSelect
      defaultValue={0}
      value={duration}
      onChange={(e) => setDuration(e.target.value)}
      inputProps={{
        name: 'month',
        id: 'duration-input',
      }}
    >
      <option value={1}>1 month</option>
      <option value={2}>2 months</option>
      <option value={3}>3 months</option>
</NativeSelect>
  </FormControl>
</Box>

     <h1 className="home-text027">
      <span>
        {dates.map((emi, index) => {
          const { date, month } = emi;
          return (
            <span key={index}>
    </span>
          );
        })}
        
      </span>
        <span>You will pay back
          <span className="loanContainer"> ${loan}</span>
          <span className="loanContainer2"> /month</span>
          </span>
    </h1>
  </div>
  );
 }
};

JavaScript – update deeply nested array of objects with the target path

I put an example of an array. The nesting level is always unknown, and children can be either undefined or an array with at least one item. Each key is always unique. I’d like to update the children of the element found by the given key. Is there any way to achieve this in JS without lodash or any other libraries?

const arr = [{
    key: '001',
    children: [{
        key: 'abc',
        children: [{
            key: 'ee',
            children: [{
                key: 'goc',
            }, {
                key: 'zzv',
                children: [{
                    key: '241',
                }],
            }],
        }],
    }, {
        key: '125',
        children: undefined,
    }],
}, {
    key: '003',
    children: [{
        key: 'ahge',
    }, {
        key: '21521',
    }],
}];

I’d like to write a function that receives a key to find the element and then updates its children field with the given children array and then returns the whole arr.

// Function that returns arr with updated the target element - how can I write this?
const mysteryFn = (arr, key, childrenToUpdate) => {
 // Do something..

 return arr;
}


const key = 'goc';
const childrenToUpdate = [{
 key: '12345',
}, {
 key: '25221a',
}];

const newArr = mysteryFn(arr, key, childrenToUpdate);

How to trigger dragend event

How do I force a dragend event to fire? I use a library that automatically adds a listener to elements which looks for a long press (for touch screen to simulate a right click event). I don’t want that to fire when a user tries to drag (but the nature of dragging means, they click and hold/long press)

I know how to set one up, but what I’d like is

instrumentInfo.addEventListener("dragstart", function (e) {
    e.preventDefault();//stop longpress working for touch screens
    e.dragend(); //not going to work
}

I understand I may get race conditions and am OK with that

how to use useLocation hook in a custom file in react js?

I have a separate file where I put the commonly used functions in my react project called MyFunctions.js . In this file, I want to use useLocation hook to get the current pathname + the query string of my current url. but it gives an error

React Hook "useLocation" is called in function "getCurrentURL" that is neither a React function component nor a custom React Hook function.

this is my code: codesandbox

// MyFunctions.js
import useLocation from "react-router-dom";

export function getUrl() {
  const location = useLocation();
  return location.pathname + location.search;
}
// App.js
import "./styles.css";
import { HashRouter as Router, Route, Routes } from "react-router-dom";
import * as fn from "./MyFunctions";
import Test1 from "./components/Test1";

export default function App() {
  const a = fn.getUrl();

  return (
    <Router>
      <div className="App">
        <h1>Hello CodeSandbox: {a}</h1>
        <Routes>
          <Route path="/" element={<Test1 />} />
        </Routes>
      </div>
    </Router>
  );
}
// Test1.js
const Test1 = () => {
  return (
    <div>
      <h1>Lorem Ipsum</h1>
    </div>
  );
};

export default Test1;

how do i fix ( “no viable alternative at input ‘DELAY'”, )

[error] script [ auto-clicker ] stopped with error in line 2 at column 6
[error] SyntaxError ( “no viable alternative at input ‘DELAY'”, )

im not sure how to fix this ive tried to make the input delay vary between 0-0.1 so that is has a alternative but it didnt work heres the code

javascript;
const DELAY = 0; const autoClickerStyleElement = document.createElement(‘style’); autoClickerStyleElement.innerHTML = ‘*{cursor: crosshair !important;}’; document.body.appendChild(autoClickerStyleElement); function addClicker(e) { if (!e.isTrusted) { return; } if (e.target.classList.contains(‘auto-clicker-target’)) { e.target.classList.remove(‘auto-clicker-target’); } else { e.target.classList.add(‘auto-clicker-target’); }document.body.removeChild(autoClickerStyleElement); document.body.removeEventListener(‘click’, addClicker); e.preventDefault(); autoClick(e.target); } function autoClick(element) { if (element.classList.contains(‘auto-clicker-target’)) { element.click(); setTimeout(() => { autoClick(element); }, DELAY); } }document.body.addEventListener(‘click’, addClicker, 0);

Are there any tools for combining several javascript/typescript files?

I’m currently working on a project that involves exporting a custom React component I made. My React component starts with one class that has several other dependencies, and those files contain other dependencies. My overall goal is to export my file and all their dependencies into a singular file that I can simply import to another react project to use my component externally. Does anyone happen to know of any available tools I could use to combine my files into one? I’ve tried using webpack but I can’t seem to be able to use my minified file externally, so if anyone has any pointers (I’m new to all of this) I would greatly appreciate them!

Turned flipper off and still getting Typedef redefinition with different types (‘uint8_t’ (aka ‘unsigned char’) vs ‘enum clockid_t’)

I’m getting this error in my React-Native iOS app:

Typedef redefinition with different types ('uint8_t' (aka 'unsigned char') vs 'enum clockid_t')

Which usually means that flipper is enabled, and is causing problems. However, in my case, flipper is off:

require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '12.0'
install! 'cocoapods', :deterministic_uuids => false

target 'Newr Remote' do
  config = use_native_modules!

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # to enable hermes on iOS, change `false` to `true` and then install pods
    :hermes_enabled => flags[:hermes_enabled],
    :fabric_enabled => flags[:fabric_enabled],
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'Newr RemoteTests' do
    inherit! :complete
    # Pods for testing
  end

  # Enables Flipper.
  #
  # Note that if you have use_frameworks! enabled, Flipper will not work and
  # you should disable the next line.
  # use_flipper!()

  #post_install do |installer|
  #  react_native_post_install(installer)
  #  __apply_Xcode_12_5_M1_post_install_workaround(installer)
  #end
end

I’ve already tried a pod install. What could I be missing?

My javascript starts at later hours than I need it to

I am stuck getting this script to show certain elements during the week from 7 am to 4 pm PST and outside of that show a different element off hours and on the weekends.

I created this script but my hours are not working right. The script does not automatically start at 7 AM and automatically end at 4 PM even though I manually enter my UTC offset for Los Angeles.

The elements I am trying to show are from Unbounce so it might look a bit unfamiliar.

If anyone has any suggestions getting the hours to work correctly no matter what timezone someone in, I would really appreciate it? Thank you.

<script type="text/javascript">

var d = new Date();
var localTime = d.getTime(); 
var localOffset = d.getTimezoneOffset() * 60000; 
var utc = localTime + localOffset;
var offset = -7 
var PST = utc + (3600000*offset);
var nd = new Date(PST);  
var CurrentDay = nd.getDay();
var BusinessHours = nd.getHours();

if (CurrentDay !== 0 || CurrentDay !== 6) { 
    if (BusinessHours >= 16 || BusinessHours <= 7 ) { 

            $("#lp-pom-box-409").hide();
            $("#lp-pom-text-341").hide();
            $("#lp-pom-text-461").show();
            $("#lp-pom-button-460").show();
            $("#lp-pom-button-209").hide();

   } else {
     
            $("#lp-pom-box-409").show();
            $("#lp-pom-text-341").show();
            $("#lp-pom-text-461").hide();
            $("#lp-pom-button-460").hide();
            $("#lp-pom-button-209").show();

   }
}

</script>

Display in div content from a function which displays an array

I have a slider which will go through each functions in an array functions[], also I have another array array[] with data, when I call for a function to display data in console it shows my array[], but when I want to display the data from the array[] in div it shows undefined. What should I do?

const textContent = document.getElementById("textContent");// a div
const next = document.getElementById("next");// a button
const prev = document.getElementById("prev");// a button

const array = [
    "They both die at the end",
    "What if it's us",
    "Tuesday with Morrie",
    "Second life of Ove",
    "Flowers for Algernon",
    "The Minds of Billy Milligan",
    "The Fifth Sally",
    "The Touch",
    "Adele",
    "The Girl Before"
];

function first(){
    console.log("1");
};
function second(){
    for(item in array){
        textContent.innerHTML += `${array[item]}<br>`;
    }
};
function third(){
    console.log("3");
};
function four(){
    console.log("4");
};
function five(){
    console.log("5");
};

const functions = [
    first,
    second,
    third,
    four,
    five
];

number = 0;

function skip() {
    if(number > functions.length - 1){
        number = 0;
    }

    if(number < 0){
            number = functions.length - 1;
        }
    f = functions[number];
    textContent.innerHTML = f();
}

next.addEventListener("click", () => {
    number += 1;
    skip();
})

prev.addEventListener("click", () => {
    number -= 1;
    skip();
})