Implementing functions [closed]

  • A checkSuspect function that takes a suspect object as parameter from the data structure below. Your function should return a number
    value indicating how many of their properties match the witness
    statement. You should use conditional statements to compare the
    suspect’s properties to the statement.

  • A findGuilty function which traverses the array of suspects and returns the object representing the guilty suspect, otherwise – return
    an empty object.

There are many possible ways of carrying out your duties, but you
should complete this task using ONLY the following commands:

  • function checkSuspect(suspectObj){}
  • function findGuilty(){}
  • if()
Witness statement:

  It was last Thursday, I heard noises outside so I looked out and saw a person in the steet.They seemed to be between the age of 18 and 42 years old.I remember they had a facial tattoo.They were wearing a black overcoat.They brobably weigh between 69 and 74 kg.I 'm not quite sure. They were fairly tall, I think between a height of 155 and 210 cm. It'
s so hard to remember right now.It was very dark and I could barely see, They were carrying a red backpack.I distinctly remember that they were wearing a dotted necktie, I remember thinking that was quite unusual.I 'll never forget their blue eyes. They wore thin metallic glasses. That'
s all I know officer.

  */

var lineupLog = [{
    "name": "ERMELINDA MOHWAWK",
    "glasses": "black",
    "coat": "white fur coat",
    "tattoo": "jellyfish",
    "accessory": "metal briefcase",
    "height": 186,
    "weight": 72,
    "age": 48
  },
  {
    "name": "LARRAINE GOODBURY",
    "glasses": "very thin",
    "coat": "red parka",
    "tattoo": "sword",
    "accessory": "orange plasic bag",
    "height": 181,
    "weight": 80,
    "age": 44
  },
  {
    "name": "MAJORIE WARMAN",
    "glasses": "thin metallic",
    "coat": "black overcoat",
    "tattoo": "facial",
    "accessory": "red backpack",
    "height": 162,
    "weight": 73,
    "age": 30
  },
  {
    "name": "LINETTE TINTLE",
    "glasses": "light tan",
    "coat": "yellow poncho",
    "tattoo": "big arrow",
    "accessory": "orange tote bag",
    "height": 162,
    "weight": 77,
    "age": 35
  },
  {
    "name": "JULIANA OORIN",
    "glasses": "dark brown",
    "coat": "green army coat",
    "tattoo": "anchor",
    "accessory": "laptop bag",
    "height": 170,
    "weight": 81,
    "age": 38
  },
  {
    "name": "JACQUELINE DORCEY",
    "glasses": "red",
    "coat": "green jacket",
    "tattoo": "dark black",
    "accessory": "big black envelope",
    "height": 179,
    "weight": 65,
    "age": 38
  },
  {
    "name": "GAYLA PORTOS",
    "glasses": "white",
    "coat": "blue overcoat",
    "tattoo": "neck",
    "accessory": "black duffle bag",
    "height": 177,
    "weight": 66,
    "age": 55
  }
];

var myFont;
var backgroundImg;

function preload() {
  myFont = loadFont('SpecialElite.ttf');
  backgroundImg = loadImage("Background.png");
}

function setup() {
  createCanvas(640, 480);
  textFont(myFont);
}

// Declare both your functions here





function draw() {
  //You don't need to alter this code
  image(backgroundImg, 0, 0);

  fill(255, 0, 0);
  text(findGuilty().name + " is guilty!", 60, 80);
}

:

  • A checkSuspect function that takes a suspect object as parameter from the data structure below.
    Your function should return a number value indicating how many of their properties match the witness statement.
    You should use conditional statements to compare the suspect’s properties to the statement.

  • A findGuilty function which traverses the array of suspects and returns the object representing the guilty suspect,
    otherwise – return an empty object.

There are many possible ways of carrying out your duties,
but you should complete this task using ONLY the following
commands:

  • function checkSuspect(suspectObj){}
  • function findGuilty(){}
  • if()

Updating a clip-path in d3.js?

In my recent project, I am interested in creating a clip-path which moves with my mousemove. My initial idea was simply to select and re-position the ellipsis with its attributes cx and cy using the mousemove coordinates, then selecting the rectangle and re-initializing its clip-path attribute.

This, however, does not seem to work. The only workable solution I have found so far is to delete the rectangle and the clip-path, then re-initializing them at the new coordinates. This works fine for the simple test-case below, but in my actual experiment, the object I’ll try to clip is an externally loaded svg, and having to re-load it every mouseover tick might be prohibitively expensive.

Do you have any suggestions on how to achieve the same effect as I have shown below without re-initializing everything?

<!DOCTYPE html>
<html>

  <head>
    <script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    
    <style>

    </style>
  </head>

<!-- Create a div where the graph will take place -->
<div id="my_datavisualization">
  <svg id="click" xmlns="http://www.w3.org/2000/svg">
      <defs>
          <g id="pointer" transform="scale(0.5)">
              <circle cx="0" cy="0" r="20" id="dragcircle" />
          </g>
      </defs>
  </svg>
</div>



  <body style='overflow:hidden'>
  
    
    <script>
    
        // Get the viewport height and width
      const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
      const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
      
      // Fit to viewport
      var height            = vw*0.7;
      var width             = vw;
      
      // Create the canvas. We will use only part of it for the main plot
      var svg = d3.select("#click") // This selects the div
          .attr("width", width) // This defines the canvas' width
          .attr("height", height) // This defines the canvas' height
      
      
        
      
      // define the clipPath
      svg.append("clipPath")       // define a clip path
          .attr("id", "ellipse-clip") // give the clipPath an ID
        .append("ellipse")          // shape it as an ellipse
          .attr("cx", 175)         // position the x-centre
          .attr("cy", 100)         // position the y-centre
          .attr("rx", 100)         // set the x radius
          .attr("ry", 50);         // set the y radius

      // draw clipped path on the screen
      svg.append("rect")        // attach a rectangle
          .attr("id","cliprect")
          .attr("x", 125)        // position the left of the rectangle
          .attr("y", 75)         // position the top of the rectangle
          .attr("clip-path", "url(#ellipse-clip)") // clip the rectangle
          .style("fill", "lightgrey")   // fill the clipped path with grey
          .attr("height", 100)    // set the height
          .attr("width", 200);    // set the width
      
      
      // Shift the marker around on mouseover; restrict it to the contour
      var movex
      var movey

      svg
        .on("mousemove", function () {
        
            // Get the current mouseover coordinates
            movex = d3.event.x;
            movey = d3.event.y;

          // The only way I get this to work right now is by removing the previous clipped shape, then re-adding it
          d3.select("#cliprect").remove()
          d3.select("#ellipse-clip").remove()
          
          // define the clipPath
          svg.append("clipPath")       // define a clip path
              .attr("id", "ellipse-clip") // give the clipPath an ID
            .append("ellipse")          // shape it as an ellipse
              .attr("cx", movex)         // position the x-centre
              .attr("cy", movey)         // position the y-centre
              .attr("rx", 100)         // set the x radius
              .attr("ry", 50);         // set the y radius
            
          // draw clipped path on the screen
          svg.append("rect")        // attach a rectangle
              .attr("id","cliprect")
              .attr("x", 125)        // position the left of the rectangle
              .attr("y", 75)         // position the top of the rectangle
              .attr("clip-path", "url(#ellipse-clip)") // clip the rectangle
              .style("fill", "lightgrey")   // fill the clipped path with grey
              .attr("height", 100)    // set the height
              .attr("width", 200);    // set the width
          
          
            
          });

      
  
    </script>
  </body>

</html>

Prevent useState from multiplying eventListeners

I’m trying to create some sort of typing test, making letters be removed from a string if they have been typed correctly. My initial approach was to use a state to save the words in, and if the correct key has been pressed, remove the first letter from the string. However, this results in a lot of bugs, such as that after around 20 correct keys, the function starts to remove multiple characters from the string and when pressed on some keys, the string even starts building itself back, pressing on ‘e’ and ‘r’ in my case. It is not an infinite render, so I’m not sure why. I think what is happening is that the eventlistener is multiplying, so it starts to remove multiple letters, if I’d console log the key pressed this confirms this as well. Here is the code.

    const [words, setWords] = useState("a lot of words are put here")
    const removeLetter = (e) => {
        if (e.key === words[0]) {
            setWords((letters) => letters.substring(1));
    }
    document.addEventListener("keypress", function(e) {removeLetter(e)})

My javascript code doesn’t work, but when it is executed in the console it works

I have a problem, my javascript code does not work, I have an error in the console, but when I paste it in the console, it works perfectly. Somebody could explain me

if (document.getElementById('r1').checked){ 
    document.querySelector('.title-opa-dentals').classList.add('opacity')
};
.opacity{
    opacity: 1!important;
}
<div class="box-slider slides">
    <input type="radio" name="r" id="r1" checked>
    <input type="radio" name="r" id="r2">
    <input type="radio" name="r" id="r3">
    <div class="select-1"></div>
    <div class="select-2"></div>
    <div class="select-3"></div>
    <div class="navigation">
        <label for="r1" class="bar">
        <a class="title-opa-dentals">Dentals</a> 
        </label>
        <label for="r2" class="bar">
        <a class="title-opa-jewellers">Jewellers</a>
        </label>
        <label for="r3" class="bar">
        <a class="title-opa-industrials">Industrials</a>
        </label>
    </div>

How to handle AJAX resquest with express js

I am trying to handle a ajax request using expressjs, when i click the any anchor tag then the page fully reloads and didn’t get the hand ajax request on client side. I need when i click any of these link then it should handle by client side using fetch api

This is html stucture

<header id="main-header">
  <nav>
    <ul>
      <li class="nav-bar"><a data-urlid="" href="/">Home</a></li>
      <li class="nav-bar"><a data-urlid="about" href="/about">About</a></li>
      <li class="nav-bar"><a data-urlid="achievements" href="/achievements">Achievements</a></li>
      <li class="nav-bar"><a data-urlid="gallery" href="/gallery">Gallery</a></li>
      <li class="nav-bar"><a data-urlid="contact" href="/contact">Contact</a></li>
    </ul>
  </nav>  
</header>

This is controller

const home = (req, res) => {
   res.json({message:"success"})
};

this is router for get home page

router.get("/", danceController.home);

Trying to handle ajax request using vanilla js

const navBars = document.querySelectorAll(".nav-bar");

async function head(event) {
  event.preventDefault();
  const url = event.target.dataset.urlid;

    const responseData = await fetch(`/${url}`, {
        method: "GET",
        headers: {"Content-Type":"text/html"}}).then((response) => {
            console.log(response);
        });
    
    // console.log(responseData);
};

for (const navBar of navBars) {
    navBar.addEventListener("click", head)
}

Shopping cart with a selected value in cookie using JavaScript

I need some help with my Shopping Cart. I’m using cookie to create it and my code is working, but there is one thing missing.Right now when I add a couch in my cookie, my cookie looks like this :

[{"colors":["Black/Yellow","Black/Red"],"_id":"415b7cacb65d43b2b5c1ff70f3393ad1","name":"Kanap Cyllène","price":4499,"imageUrl":"http://localhost:3000/images/kanap02.jpeg","description":"Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.","altTxt":"Photo d'un canapé jaune et noir, quattre places"}]

And my console.log gives me this :

[{…}]
0: {colors: Array(2), _id: '415b7cacb65d43b2b5c1ff70f3393ad1', name: 'Kanap Cyllène', price: 4499, imageUrl: 'http://localhost:3000/images/kanap02.jpeg', …}

The user is able to add the couch he selected in the cookie but he has several color options and I want my cookie to take the value selected by the user because for the moment my cookie is an array with the selected couch and in this array there is the array of the several color choices. I tried to simply add the value in my array but it doesn’t work. I tried this :

let couchColor = document.getElementById("colors").value
            if(cart === null) {
                cart = [couch + couchColor]
                console.log(cart)
            }

But with this my cookie doesn’t understand couch anymore and looks like this :

["[object Object]Black/Yellow"]

Can someone help me please ? I want the array of color to be replaced by the value selected by the user. Here is my code :

.then((couch) => {
        let newImage = document.createElement("img");
        newImage.src = couch.imageUrl;
        newImage.alt = couch.altTxt;
        image[0].appendChild(newImage);
        title.innerHTML = couch.name;
        price.innerText = couch.price;
        description.innerText = couch.description;

// Choix couleurs

    
        for (choice in couch.colors) {
            colors.options[colors.options.length] = new Option(
                couch.colors[choice], couch.colors[choice]
            );
        }

// Ajouter produit au panier https://stackoverflow.com/questions/10730362/get-cookie-by-name

        addButton.onclick = ('click', function () {
            let cart = getCookieByName("cart")
            let couchColor = document.getElementById("colors").value
            if(cart === null) {
                cart = [couch + couchColor]
                console.log(cart)
            } else {
                cart = JSON.parse(cart)
                cart.push(couch)
            }
            document.cookie = "cart=" + JSON.stringify(cart)+";"
            })
        })
    }
    
    function getCookieByName(name)
    {
    var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    if (match) {
        return match[2];
    }
    else{
        return null
    }
}

disabled button not working properly in react

if give more than 10 characters then button should be disabled but when we give <10 character’s button should be enabled not working

import React, { useState } from "react";
export default function DropDown() {
  let [disable,setDisable]=useState(false)
  function check(){
    let inp=document.querySelector('input');
    let btn=document.querySelector('button');
    if(inp.value.length>10){
      btn.disable=true
      setDisable(true)
    }else{
      btn.disable=false;
      setDisable(false)
    }
  }
   return (
    <>
    <input disabled={setDisable} onKeyUp={check}/>
<button>click</button>
    </>
  );
}

Javascript Testing with a loop

I have quite a number of constants which I am importing with import.

Would it be considered bad practice to loop thru them and check that certain things match up when testing?

import * as allCommunicationExports from '../public/communication.min';
for (const [communicationSelectorConstant, value] of Object.entries(allCommunicationExports)) {
        it(`should have a constant named ${ communicationSelectorConstant } is a string and starts with a selector for a data attribute`, () => {
            expect(allCommunicationExports[communicationSelectorConstant]).toBeDefined();
            expect(typeof allCommunicationExports[communicationSelectorConstant]).toBe('string');
            expect(allCommunicationExports[communicationSelectorConstant].startsWith('[data-js-comms')).toBeTruthy();
            // more to come
        });
    }

Is there a possibility with javascript to show a scroll hint only at the first pageload?

I have created a simple scroll hint which disappears by mousedown. My goal is that the hint is only displayed the first time. When I reload the page, it should not be displayed again. Only again when the cache of the web page is cleared.

Is there a simple way to realise it with javascript?

Here is my code html code:

<div id="content" onmousedown="hideHint()">
  <div id="scroll-hint" >
    <div class="mouse">
        <span></span>
    </div>
  </div>
</div>

Here is my css:

body{
    margin: 0;
  }

  #content{
    background-color: orange;
    height: 100vh;
    width: 100vw;
  }

  #scroll-hint{
  background-color: gray;
  border-style: solid;
  height: 20vh;
  width: 20vw;
  align-items: center;
  display: flex;
  justify-content: center;
  position: fixed;
  left: 40%;
  }

  .mouse {
      display: block;
      width: 23px;
      height: 40px;
      border-radius: 13px;
      border: 2px solid blue;
      position: absolute;
      left: 50%;
      margin: 0 auto 0 -14px;
      background-color: white;
  }


  span {
      display: block;
      margin: 6px auto;
      width: 3px;
      height: 7px;
      border-radius: 100%;
      background: blue;
  }

And here is my javascript:

function hideHint() {
    document.getElementById("scroll-hint").style.display = "none";
  }

user not defined for onAuthStateChanged in Firebase with custom hook

I built a custom hook to get a user from firebase:

export function useAuth() {
  const [currentUser, setCurrentUser] = useState<any>();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, async (user) => {
      if (user === null) {
        setCurrentUser(null);
      } else {
        const u = await getDoc(doc(db, "users", user.uid));
        const name = u.data().name;
        setCurrentUser(user === null ? null : { ...user, name: name });
      }
    });
    return unsubscribe;
  }, []);

  return currentUser;
}

In my components I use it as:

const currentUser = useAuth();
useEffect(() => {
    const localScore = JSON.parse(localStorage.getItem("score"));
    setPush(!(localScore[currentUser.name] === tasks.length));
                                  // ^ TypeError: Cannot read properties of undefined (reading 'name')
  }, []);

I think I get the error, because when the components gets rendered the first time, there is no currentUser. But I load the component after the user logged in (what sets the user), thus I am confused.

I think I need to await the user somehow, but how?

What causes Chrome Performance Tools occupying an immense amount of CPU when web workers are involved?

The problem I’m having can be boiled down to this:

The setup

There are two files: index.html and worker.js.

In index.html:

<script>
foo = new Worker("worker.js");
</script>

Worker.js contains no code in this example. In my actual code, the worker will wait for messages, but the only important part here is that it is not killed.

The problem

When I now go to the Performance tab within Chrome Dev Tools, and hit “Start profiling and reload page”. The workers will persistently use an immense amount of CPU time, even after the profiling has finished. That amount can be as high as 100% core utilization per worker.

The problem scales with the number of web workers and as soon as I kill them, the utilization stops. So I can be sure, that it is indeed the workers who cause this problem.

My questions

  • What causes this behaviour? Does the profiler inject some code into the workers themselves, which is not removed after the profiling finished?
  • What can I do about it?
  • Can I maybe somehow turn off the profiling for web workers while profiling my webapp?

This problem might sound minor, since it only happens when profiling and not on the users PCs, but my app uses as many web workers as the client has CPU cores, who all wait for jobs instructions. While debugging profiling that utilizes 100% of my CPU. And as I said, after profiling has finished, it doesn’t stop. I don’t want to kill the workers via console, every time I profile my app. I also don’t want to have my CPU run at 100% for hours when I forget to kill the workers after profiling and leaving the PC.

Changing my app, so that the workers are started and killed per job is not an option.

AppScript Problem using GmailApp.SendEmail function

Background:
I’m currently taking a Visual Programming class where we use Google Sheet/ AppScript to create a simple system using triggers and function.

Problem: I’m trying to mimic and create a simple online ordering system where it will send emails to customers once our “restaurant” receives, preparing and delivering their order using GmailApp.SendEmail function. I put some functions on the AppScript but I just cant get what I want to do in code. Here is what I have so far: ( I created a custom menu for each function. For example, once “Preparing Order” button is clicked, the customer will receive an email stating that their order is being prepared”

function prepareOrder(){

// send msge to customer that a Kitchen is preparing the order
// 


}

function completedOrder() {
// send msge to customer that the Kitchen has completed the order 
// 
}

function readyForDelivery()
{
// send msge to customer that the delivery person is preparing the order for delivery 
// 
// 
}

function deliveredOrder() {
// send msge to customer that the order has been delivered and completed with a receipt
//
//  
} 

Goal: As mentioned before, Im a beginner at this and my path is probably silly but my goal is to somehow automate and grab customer info (email) from the spreadsheet to then use that information to send an email and create a receipt/invoice of their order.

AppScipt_SS

Spreadsheet_SS

Integrating multiple analytics libraries in my web app

I have to integrate multiple tracking libraries for ex: (Exponea, Azure Application insights)
One is a marketing tracking SDK and another is a general tracking sdk used for getting general metrics, will also be integrating another tracking sdk (ex: Google Analytics) for a different purposes.

Because of the above, I might have to include other libraries in the future, Just want to know is there any industry-standard way to implement the above And also make these libraries loosely couple with my application?

I have gone through Google Tag manager, wherein I can configure which page can load 3rd party sdk, which looks okie, but not sure about the other advantages I would get out of it. Once integrated i don’t require any code change if i want to add a new event to my web app?

Thoughts?

Looking for Javascript code to ignore the outliers value provided to it during input

I want to try the The tests in test/average.test.js express the functionality of the average function.
Consider this situation: In IoT applications, analog sensors will report occasional outliers. ‘Outliers’ are values so small or so large, they aren’t expected to happen. We need new functionality to ignore these outliers.
I’ll need thresholds to recognize outliers: Think of sensing battery-temperature values and determine reasonable values.

heres the code for average.test.js:-

const {expect} = require('chai');
const {average} = require('../average');

it('computes average of a list of numbers', ()=> {
  // floating point numbers cannot be compared for equality,
  // hence allowing a delta tolerance
  expect(average([1, 2, 3, 4])).to.be.approximately(2.5, 0.01);
});

it('reports the average as NaN on an empty list', ()=> {
  expect(average([])).to.be.NaN;
});

it('ignores NaN in the input', ()=> {
  expect(average([1, NaN, 2])).to.be.approximately(1.5, 0.01);
});

And Heres the code for average.js file :-

function average(numbers) {
  
  //Used Filter Function to clear out any Garbage inputs.
   numbers=numbers.filter(Boolean);
   return numbers.reduce((p, c)=> p + c, 0) / numbers.length;
}

module.exports = {average};