Remove First and Last Double Quote From JSON Array

Here i have one big array that has multiple arrays inside. I need to remove double quotes from each array. I tried all different methods to pull out quotes but none seem to work.

Current code produces this result:

[
  ["1,jone,matt,ny,none,doctor"],
  ["2,maria,lura,nj,some,engineer"],
  ["3,paul,kirk,la,none,artist"]
]
    const storeArray = [];

    for(var i = 0; i < results.length; i++) {

      var finalArray = results[i].id + "," + results[i].name + "," + results[i].lastname + "," + results[i].address + "," + results[i].status + "," + results[i].about;

      storeArray.push([finalArray]);
    }

    res.send(storeArray);

Javascript: Creating dictionary array using variables for keys and values

I am trying to create a dictionary from some lists using the .push() method.

The result I am trying to achieve is:

{
  "departTo": {
    1: 1.159,
    2: 4.156,
    3: 9.185,
    3: 10.158,
    4: 2.158
  },
  "departTo": {
    1: 2.586,
    2: 5.518,
    3: 11.584,
    3: 7.819,
    4: 3.991
  }
}

Below is a sample of code of what I am trying to do:

console.group("Running Script 1...");

var select_array = [];
var arrive_from, info

var selection_type = ["departTo", "arriveFrom"];
var data_lists_depart = [[1, 1.159], [2, 4.156], [3, 9.185], [4, 10.158], [5, 2.158]];
var data_lists_arrive = [[1, 2.586], [2, 5.518], [3, 11.584], [4, 7.819], [5, 3.991]];

selection_type.forEach(function (selection, i) {
    console.log("selection", i + ": ", selection);
    if (selection === "departTo") data_lists = data_lists_depart;
    else if (selection === "arriveFrom") data_lists = data_lists_arrive;
    data_lists.forEach(function (data_list, ii) {
        console.log("   data_list", ii + ": ", data_list);
        key = data_list[0];
        val = data_list[1];
        select_array.push({selection: {key: val}});
    })
})
console.log("select_array: ", select_array);

console.groupEnd("Running Script 1...");

The result I am getting from the above code is:

[
  {"selection": {"key": 1.159}}, 
  {"selection": {"key": 4.156}}, 
  {"selection": {"key": 9.185}}, 
  {"selection": {"key": 10.158}}, 
  {"selection": {"key": 2.158}}, 
  {"selection": {"key": 2.586}}, 
  {"selection": {"key": 5.518}}, 
  {"selection": {"key": 11.584}}, 
  {"selection": {"key": 7.819}}, 
  {"selection": {"key": 3.991}}
]

Any assistance in getting this into the format I need will be greatly appreciated.
Thank you.

splice() is not emptying the array

Below code should return empty array but it is returning Banana,Banana,Banana

const fruits = ["Banana", "Banana", "Banana", "Banana", "Banana", "Banana"];

fruits.map((ele) => {
  if (ele === "Banana") {
    fruits.splice(0, 1)
  }
})

document.getElementById("demo").innerHTML = fruits;
<div id="demo"></div>

Component re-render on state change not happening

I have a react app similar to what is shown in this codesandbox link https://codesandbox.io/s/eatery-v1691

Clicking the Menu at the bottom center of the page renders the MenuFilter component.

The MenuFilter component in turn uses a checkbox component to render several check boxes & the checked status of these checkboxes depends on the selectedMeals prop that I pass to the MenuFilter in app.tsx.

I read that when the state is passed as a prop, the re-rendering happens as soon as the state changes but this is not happening.

The selectedMeals state is initialized with allItems and then managed such that when any other items is click, that items is set & allItems and these individual items can be several at once. The state management works fine but the checkbox is not getting updated based on the state!

If you however, click cancel (ok button does not do anything yet) & then click Menu button again, only the values in the selectedMeals prop are rendered.

See the video here (https://youtu.be/Zmfc0MQGaIU this is the full app, codesandbox app is representation of this but not the same) where the state change (allItems gets removed & when allItems is checked other items get removed) works perfectly but the check boxes are not re-rendering appropriately

What am I doing wrong & more importantly how do I get the result I want?

I initially put the question here re-render as soon as the state is changed but there was no sandbox for it & since the sandbox is different from what I put in that question, I created a new question. THanks.

Is there a remote DOM manipulation library like drab for elixir but language-agnostic? [closed]

Drab is a library that elixir phoenix liveview uses to remotely control the DOM in the browser. Looking through their code, it seems to contain a javascript library for making the connection to the backend and accepting events. It seems to be completely tied to elixir though, it even uses elixir’s templates to inject values into the javascript code.

So since drab isn’t really an option here, is there another frontend library that lets you control the browser dom remotely through websockets without a reliance on elixir?

React onClick logic works in desktop browsers but not in mobile

I am trying to implement a profanity filter on an app I am building that deals with twitter-like posts.

The check will loop through each swear word in a list of words, and check the content against what the user has entered into the form.

The app uses Chakra UI useToast to display a message if a swear is detected or the fields are not all filled out. The logic is simple:

import { swearWord } from "../swear-words";
import { useToast } from "@chakra-ui/react";

...
...
...
// onClick function for adding a new post:

const addPost = async () => {
if (!name || !title || !type || !content) {
  toast({
    title: "Please fill out all fields!",
    status: "error",
    duration: 2000,
    isClosable: true,
  });
  return;
}
// THIS IS THE PROBLEMATIC CHECK THAT DOESNT WORK ON MOBILE
for (let swear of swearWord) {
  if (
    title.includes(swear) ||
    title.includes(swear.toUpperCase()) ||
    name.includes(swear) ||
    name.includes(swear.toUpperCase()) ||
    content.includes(swear) ||
    content.includes(swear.toUpperCase())
  ) {
    toast({
      title:
        "Some of the language you've used in this post is considered aggressive.",
      status: "error",
      duration: 5000,
      isClosable: false,
    });
    toast({
      title:
        "If you have a problem you'd like addressed, please contact the Administrators, but you may not take it out on the community via this board.",
      status: "error",
      duration: 5000,
      isClosable: false,
    });
    postContext.displayForm(); // close the form if swear word found
    return; // return and do not proceed with function execution

  }
}

const ipResponse = await fetch("https://api.ipify.org?format=json"); // get user IP
const ipAddress = await ipResponse.json(); // save userIP

// construct post.
const newPost = {
  author: name,
  title: title,
  type: type,
  content: content,
  ipAddress: ipAddress,
};
postContext.displayForm(); // close the form after successful submission.
postContext.addPost(newPost); // defer to app-wide context to make appropriate API calls
  };

The problem

When doing this on a desktop browser, it works. The message is displayed, and the function ceases execution.

When I open both the local and deployed version on my phone (makes no difference) the ENTIRE for loop where it’s checking for these words is completely skipped.

I know it is skipped because I can add an alert before the for loop, in the for loop, and after the for loop and only the one before and after will display, but not the one in the for loop. The function never ceases execution, and posts with profanity are sent to the API and allowed into the database and displayed as a new post.

This is what the outcome SHOULD look like:

enter image description here

On mobile this entire for loop check is skipped.

Has anyone else encountered this and knows why? It doesn’t make any sense to me why something would work on desktop but not on mobile when every other aspect of the same javascript code is working without fail. I don’t know what it is that could change so drastically that the simple act of pulling the same website up on a mobile phone causes an entire block of javascript to just cease existence.

Is there a way to make a rectangular area 0 alpha (transparent) after it has been drawn on to?

I’ve seen lots of questions asking how to draw a semi-transparent rectangle or other shape onto canvas after it’s already been drawn to. My problem is that I want a rectangular area to be 0 alpha, but it seems to draw just nothing on top of what is there. I understand why that is (you are drawing 0 alpha on top of something that is already drawn), but I want those pixels 0 alpha. There has to be way.

Basically, I want to define an area that has 0 alpha after the canvas has already something drawn to it.

function fillPreviewClearColor(x,y)
{
    ctx2.beginPath();
    ctx2.rect(x, y, 10, 10);
    ctx2.fillStyle = "rgba(255, 255, 255, 0.0)"; // I want NOTHING here
    ctx2.fill();    
    ctx2.restore();
}

How do I trigger firebase database?

        <div class="namaz" id="zora">Zora: </div>
        <div class="namaz" id="izlazak">Izlazak sunca: </div>
        <div class="namaz" id="podne">Podne: </div>
        <div class="namaz" id="ikindija">Ikindija: </div>
        <div class="namaz" id="aksam">Akšam: </div>
        <div class="namaz"id="jacija" >Jacija: </div>

Inside of these div’s there’s a time (eg 15:36) that I withdrew from a certain API, how do I send a trigger to the firebase database using javascript that will change just one variable when the time is equal to that one in the div?

function fetchData() {
    fetch("https://api.vaktija.ba/")
    .then(response => {
        return response.json();
    })
    .then(data => {
        const arr = data.vakat;
        const elements = document.getElementsByClassName("namaz");
        Array.from(elements).forEach((element, index) => {
           element.innerText = `${element.innerText} ${arr[index]}`;
        })
        
    })
    .catch(error => {
        console.log(error)
    });
}  
    

This is a function I’m using for getting the data from the API and placing it inside of the div’s.

cool-vaktija-default-rtdb
     aktivno: "nije"

This is the variable value. From “nije” to “jest” or something else.

https://cool-vaktija-default-rtdb.europe-west1.firebasedatabase.app/

And the link for it.

Does V8 monitor the execution of optimized machine code?

AFAIK, there are roughly two kinds of code objects in V8. One is javascript bytecode interpreted by Ignition, and the other is machine code which is compiled & optimized by Turbofan. According to the execution/frames.h, V8 constructs a different stackframe for each kind of code object. It means V8 should know the kind of the callee before it executes it.

When unoptimized code(JS Bytecode) calls the optimized one, I guess that Ignition could handle the case properly to build a new stackframe for an optimized one.

However, when the optimized code calls the unoptimized one, I’m curious about how V8 determines whether callee is unoptimized or not. In general, machine code is literally executed by the processor directly. Thus nothing can help V8 determine the kind of callee before it execute the call instruction.

Also, in my understanding, V8 should trace the execution to detect whether some code dependency is compromised and to mark or deoptimize the invalidated code objects. I think it also requires v8 to monitor the execution of machine code.

So my question is:

  1. Does V8 monitor the execution of (optimized) machine code? If so, how does it happen?

  2. If 1 is false, then how does V8 check the invalidation of code dependency or detect whether the callee is compiled or not?

Error with no message for React useNavigate()

I’m creating a project with React/Django, both of which I am very new to. Currently, I am trying to have the a button on the home page redirect to another page, which is generated on click. When I load the home page, even before I push the button, I get an error with useNavigate(). There is no message with the error. Here is my code in HomePage.js

import React, { Component } from 'react';
import { BrowserRouter as Router, Routes, Route, Link, Redirect,useParams,useNavigate} from 'react-router-dom';
import RoomPage from "./RoomPage";
import ResultsPage from "./ResultsPage";
import { Button, Grid, Typography, TextField, FormControl, FormHelperText, Radio, RadioGroup, FormControlLabel } from '@material-ui/core';

const HomePage = () => {

    try{
        const navigate = useNavigate();
    } catch(error){
        console.log(error);
    }
    const handleRoomButtonPressed=async()=>{
        
        const requestOptions = {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify({
                //votes_to_skip: this.state.votesToSkip,
                //guest_can_pause: this.state.guestCanPause,
              }),
        };
        fetch("/api/create-room",requestOptions)
            .then((response) => response.json())
            .then((data)=>navigate("/room/" + data.code));

    }

    return (
            <Router>
                <Routes>
                    <Route path="/room/:code" element = {<RoomPage/>}/>
                    <Route path="/results/:code" element = {<ResultsPage/>}/>
                    <Route path="/" element = {
                        <Grid container spacing = {1}>
                            
                            <Grid item xs={12} align = "center">
                                <Typography component="h4" variant="h4">
                                    Project Name
                                </Typography>
                            </Grid>
                            
                            <Grid item xs={12} align = "center">
                                <FormControl component = "fieldset">
                                    <FormHelperText>
                                        <div align = "center">
                                            Push the button to create a new room.
                                        </div>
                                    </FormHelperText>
                                </FormControl>
                            </Grid>

                            <Grid item xs={12} align = "center">
                                <Button color = "primary" variant = "contained" onClick={handleRoomButtonPressed}>
                                    Create a room
                                </Button>
                            </Grid>

                        </Grid>
                    
                    }/>
                </Routes>  
            </Router>

        
        );

}
export default HomePage;

The error shown is:

Error
    at invariant (index.js:46:20)
    at useNavigate (index.js:363:40)
    at HomePage (HomePage.js:23:83)
    at Ch (react-dom.production.min.js:157:137)
    at ck (react-dom.production.min.js:267:460)
    at bk (react-dom.production.min.js:250:347)
    at ak (react-dom.production.min.js:250:278)
    at Tj (react-dom.production.min.js:250:138)
    at Lj (react-dom.production.min.js:243:163)
    at Jg (react-dom.production.min.js:237:175)

How to use nested property decorators in Typescript without one overriding the other?

I am creating my own Typescript decorators for validation, but they are not working together, only the first decorator is activated, the second is ignored. The property errors should have a value, because the length passed is less than 3 characters, but is returning undefined.

function IsMoreThan(length: number) {
  return (target: any, propertyKey: string) => {
    let val = target[propertyKey];

    const getter = () => val;
    const setter = (value: string) => {
      if (value.length <= length) {
        Object.defineProperty(target, 'errors', {
          value: `${propertyKey} must be more than ${length} characters`,
          configurable: true
        });
      } else {
        val = value;
      }
    };

    Object.defineProperty(target, propertyKey, {
      get: getter,
      set: setter,
      configurable: true,
    });
  };
}

function IsString() {
  return (target: any, propertyKey: string) => {
    let val = target[propertyKey];

    const getter = () => val;
    const setter = (value: string) => {
      const varType = typeof value;
      if (varType !== 'string') {
        Object.defineProperty(target, 'errors', {
          value: `${propertyKey} must be a string, received ${varType}`,
          configurable: true
        });
      } else {
        val = value;
      }
    };

    Object.defineProperty(target, propertyKey, {
      get: getter,
      set: setter,
      configurable: true
    });
  };
}


class CreateUserSerializer {
  @IsString()
  @IsMoreThan(3)
  username: string;
  
  constructor(username: string) {
    this.username = username;
  }
}

const user = new CreateUserSerializer('aa');
console.log(user.errors);

Here is a playground with the code for easier testing: TS Playground

Javascript functions are cutting in and out

I have one issue that is a recurring thing every time I work in Javascript, which is that my code seems to be cutting in and out, depending on whether I scroll, resize the screen, reload, etc. It even seems like the speed of which I scroll seems to be a factor (even though I am, in this situation, trying to create a scroll effect, which does work as long as I scroll slowly). I have tried to figure out work arounds almost constantly since starting coding JS, but I can’t even figure out why any of this is happening, and I don’t even know what to good to find the answers.

Generally, when I create functions, I try to use the following structure

document.addEventListener("click", function(functionName) { function content });

However, this really only seems to work with click effects, and maybe hover. for scroll effects, because resizing the screen will cause weird things to happen, I have tried using the following structure

function functionName() { function content };

document.addEventListener('scroll', functionName);
window.addEventListener('load', functionName);
window.addEventListener('resize', functionName); 

This generally works better, and generally prevents screen resizing from interfering too much with scroll effects. However, it makes the code what I am seeing very jumpy and glitchy.

Is there a better way to do this, so that I am a scroll effect will always appear how it should, regardless of whether the screen resizes loads or scrolls, etc.? also, it there a way to make the code work better without having three separate event listeners to activate a single function?

jest.toThrow unable to catch exception?

I have a simple function as below

function foo({ platform }) {
  if (platform === 'all') {
    throw new Error('Platform value can only be android or ios');
  }
  
  return `${platform}`;
}

Then I wrote unit testing as below

it('should return correct result with platform', () => {
    expect(foo({ platform: 'ios' })).toBe('ios');
    expect(foo({ platform: 'android' })).toBe('android');
    expect(foo({platform: 'all'})).toThrow(new Error('Platform value can only be android or ios'));
  });

The test actually failed due to last test case without any useful information

 FAIL  src/utils/__test__/foo.test.ts
  ● foo() › should return correct result with platform

    Platform value can only be android or ios

      16 | }) {
      17 |   if (platform === 'all') {
    > 18 |     throw new Error('Platform value can only be android or ios');
         |           ^
      19 |   }
      20 |   
      21 |   return `${platform}`;

      at xx (src/utils/foo.ts:18:11)

I’ve also tried to wrapped the entire expect with try catch block but the test is not passing either