Implementing Euclidian Algorithms using JavaScript

We are going to implement the Euclidean algorithms using JavaScript. The given code is very sufficient for 2 to 3 parameters. Does this code will help us while tacking with multiple number of paraments, it will effect computational cost or not?, the algorithm will be generalized or not?

const euclideanAlgorithm = (val1, val2) => {

  const val1Abs = Math.abs(val1);
  const val2Abs = Math.abs(val2);
  
  return val2Abs === 0 ? val1Abs :  euclideanAlgorithm (val2Abs, val1Abs % val2Abs)

};
console.log(euclideanAlgorithm(5,3));
document.write(euclideanAlgorithm(5,3));

Running 5 countdowns successively in React

I have a countdown, I would like the countdown to run from 5 seconds to 0 and then start again, but this time running down from a different time.

In more clearer terms; I have 5 phases my timer will go through the clock will start off in phase 1, running from 5 seconds to 0. After the clock hits zero, I want to set the state to stage 2 and then run the clock from 6 seconds to 0, then set the state to phase 3, run the clock from 7 to 0, then phase 4, run from 8 to 0 and then finish at stage 5 running from 9 seconds to 0.

This is what I have tried :

const renderTime = ({ remainingTime }) => {
  if (remainingTime === 0) {
    return <div className="timer">Too late...</div>;
  }

  return (
    <div className="timer">
      { /* <div className="text">Remaining</div> */}
      <div className="value">{remainingTime}</div>
      { /* <div className="text">seconds</div> */}
    </div>
  );
};

const Timer = (props) => {
  const [ timer, setTimer ] = useState(5)
  const { remainingTime } = renderTime;
  const [stage, setStage] = useState(1)
  console.log(renderTime)
//  let text = document.querySelector('.value').innerText
//  console.log(text)

  const timerMap = {
        2: 6,
        3: 7,
        4: 8,
        5: 9
    }
  const changeTimer = (timer, stage, setStage) => {
        while (stage >= 5) {
            if(timer === 0) {
                setStage(stage+1)
                setTimer(timerMap[stage])
            }
            return timer
        }
  };

  return (
    <div className="App">
      <div className="timer-wrapper">
        <CountdownCircleTimer
          isPlaying
          duration={changeTimer(timer)}
          colors={["#004777", "#F7B801", "#A30000", "#A30000"]}
          colorsTime={[10, 6, 3, 0]}
          onComplete={() => ({ shouldRepeat: true, delay: 1 })}
          size={100}
        >
          {renderTime}
        </CountdownCircleTimer>
      </div>
    </div>
  );
};

I am getting the error message:

Warning: Received NaN for the `strokeDashoffset` attribute. If this is expected, cast the value to a string.

Would appreciate any help

How do I convert a serial number which was initially a date to the number of days that the date initially had?

First I have a date (format of : dd, mm, yyyy) ex : 21, 3, 2012 and I converted it to a serial number which in this case would be 40988. Now for my problem I wanna find an algorithm that returns the number of days given initially so in the example it would be 21. This is the code that I used to convert the date to the serial number :

      //intYears, intMonths, intDays are parameter variables
      var serial = 0

      //365 years in array
      var arrNormalYears = new Array()
      for (let i = 1900; i < intYears; i++) {
         arrNormalYears.push(i)
      }

      //Count the number of normal years excluding the 
      //parameter year (intYear)

      //the function numberOfDaysYear checks for us if the 
      //year is a leap year or a normal year

      var normalYears = 0
      for (let j = 0; j < arrNormalYears.length; j++) {
         if (numberOfDaysYear(arrNormalYears[j]) == 365) {
            normalYears += 1
         }
      }
      //multiply the count and add it to serial

      serial += normalYears * 365


      //Same process for leap years

      var arrLeapYears = new Array()

      for (let m = 1900; m < intYears; m++) {
         arrLeapYears.push(m)
      }

      //Count the number of leap years
      var leapYears = 0
      for (let a = 0; a < arrLeapYears.length; a++) {
         if (numberOfDaysYear(arrLeapYears[a]) == 366) {
            leapYears += 1
         }
      }

      serial += leapYears * 366


      //Now including the parameter variable intYear
      
      //Using the same process as above except this time 
      //its for the months

      var arrMonths = new Array()
      for (let k = 1; k < intMonths; k++) {
         arrMonths.push(k)
      }

      //Here the function numberOfDaysMonth gives us the 
      //number of days for the specific month, it also 
      //checks if it's a leap year 
      //also excluding the last month

      for (let x = 0; x < arrMonths.length; x++) {
         if (numberOfDaysMonth(arrMonths[x]) == 31) {
            serial += 31
         }
         else if (numberOfDaysMonth(arrMonths[x]) == 30) {
            serial += 30
         }
         else if (numberOfDaysMonth(arrMonths[x]) == 28) {
            serial += 28
         }
         else if (numberOfDaysMonth(arrMonths[x]) == 29) {
            serial += 29
         }
      }

      //Simply adding the days that are left
      serial += intDays

      return serial
   }

Now by understanding my algorithm used to turn the date into a serial number, I’m having trouble to in a way reverse the algorithm and return the days as explained above the code.

Three.js – Texture not loading even after running file through local server

Texture loading as black. I tried running the.html file through a local server (Servez) but that does not seem to be the issue. I am using visual studio code. The code seems to work fine, the console does not show any errors.

This is my code:

window.onload = function() {

    //Define the WebGL renderer:

    var renderer = new THREE.WebGLRenderer(); //specify the we will use WebGL
    renderer.setSize( 800, 600 ); //scene size (Width, Height)
    document.body.appendChild( renderer.domElement );


    //Initialize (create) the scene:

    var scene = new THREE.Scene();


    //Define the camera:

    var camera = new THREE.PerspectiveCamera(
        35,             // Field of view
        800 / 600,      // Aspect ratio
        0.1,            // Near plane
        10000           // Far plane
    );
    camera.position.x= 0;  //default value anyway
    camera.position.y= 0;  //default value anyway
    camera.position.z = 300;
    camera.lookAt( scene.position );


    //Define the objects for the scene:

   var skygeo = new THREE.SphereGeometry(150, 40, 20);
   var skytexture = new THREE.TextureLoader().load("sky.jpg");
   var skymat = new THREE.MeshBasicMaterial({map:skytexture});
   skymat.side = THREE.Backside;
   var skydome = new THREE.Mesh(skygeo, skymat);
   scene.add(skydome);

    // create a point light:
    var pointLight = new THREE.PointLight(0xFFFFFF);
    // set the light position:
    pointLight.position.x = 10;
    pointLight.position.y = 50;
    pointLight.position.z = 100;
    // add the light to the scene:
    scene.add(pointLight);

    // it renders the scene:
    renderer.render( scene, camera );

};

I found here(https://discourse.threejs.org/t/texture-loading-not-working-on-server/14910/10) that it may be because the image files were corrupted. I also found somewhere else that it may be because of browser extensions like AdBlock, but removing extensions did not fix it.

What is the reason for this?

Dynamic height of sections inisde container. Fill height of divs inside the container

I have a container that either has one or three sections. Inside each sections I have table and there is list of rows inside the table. I want to make all the height of the sections dynamic such that it occupies the entire space. If there are more tables records inside the section than I need to add scroll to table to scroll records. But at all times the entire height should be filled inside the container. How can I have min and max-height for all sections.

Design scenario If there are 2 sections instead of 3: Red is container and blue are sections which contains table.

enter image description here

The structure

Container
      section1
        table
      section 2
        table
      section 3
        table
  

Function take in array of string return only strings with that have number(s) in them. Or return empty array if none

The function has 1 parameter: an array. It should iterate through the array and return strings that contain a number in them. If none of them have an number it will return an empty array.

The code I have written so far seems too verbose. Sometimes it does not return the correct value. I am looking for any ways to shorten the code or improve it.

function numInStr(arr) {
    var stringsWithNum = [];
  for(var x = 0; x < arr.length - 1; x++) {
    for (var y = 0; y < arr[x].length - 1;y++) {
      //console.log(typeof arr[x][y]);
            if('0123456789'.indexOf(arr[x][y]) !== -1) {        
                stringsWithNum.push(arr[x]);
        break;              
      }
    }
  }
  return stringsWithNum;
}

JavaScript – How to merge an array from an object to another object with the same key [duplicate]

How can I merge the array “product” from ingredients to the object with the same key (id) inside the object inside array “types” from the array “cookies”?

So that the array cookies contains the ingredients per type of cookie.

cookies = [
  {
    name: "favourites",
    types: [
      { id: 1, name: "chocolate" },
      { id: 2, name: "strawberry" }

    ]
  },
  {
    name: "others",
    types: [
      { id: 3, name: "peanut" },
      { id: 4, name: "vanilla" }
    ]
  }
];

ingredients = [
  { 
    products: [
       { name: "chocolate chips", amount: "200g" }, 
       { name: "sugar", amount: "500g" }
    ],
    cookieId: 1 
  },
  { 
    products: [
       { name: "peanuts", amount: "350g" }, 
       { name: "sugar", amount: "900g" }
    ],
    cookieId: 4 
  }
];

This is what it should look like:

cookies = [
  {
    name: "favourites",
    types: [
      { 
        id: 1, 
        name: "chocolate"
        products: [
           { name: "chocolate chips", amount: "200g" }, 
           { name: "sugar", amount: "500g" }
        ],
      },
      { id: 2, name: "strawberry" }

    ]
  },
  {
    name: "others",
    types: [
      { 
        id: 3, 
        name: "peanut"
        products: [
           { name: "peanuts", amount: "350g" }, 
           { name: "honey", amount: "900g" }
        ],
       },
      { id: 4, name: "vanilla" }
    ]
  }
];

Cheers!

Setting react-native-modal visibility in use effect when routing to page not working

Hi I am trying to set the visibility of my react native modal in my useEffect function when I first route to a page. For some reason the state will set to true but the modal wont render. Also I tried building this in the an expo snack and it worked so i’m truly at a loss for why it wont work in my project.

Here is the full page with all the imports:

import Modal from 'react-native-modal'
import React, { useEffect, useState, useContext } from "react";
import { vh, vw } from 'react-native-expo-viewport-units';
import { TouchableOpacity, Text, View, StyleSheet } from 'react-native';
export default Lol = () => {
const [guidanceVisible, setGuidanceVisible] = useState(false);

useEffect(() => {
    setGuidanceVisible(true)
    console.log('fired')
}, [])

return (
  <View style={{ width: vw(100), height: vh(100), justifyContent: 'center', alignItems: 'center' }}>
    <Text>Hello</Text>
    {console.log(guidanceVisible)}
    <Modal
      isVisible={guidanceVisible}
      onBackdropPress={() => setGuidanceVisible(false)}
      backdropOpacity={.75}
    >
      <View style={{
        width: '100%',
        height: '100%',
        backgroundColor: 'green',
        zIndex: 10,
      }}/>
    </Modal>
  </View>
);
}

The state is getting set to true in the console.log and the fired is getting called in the useEffect.

Here is my version in the package.json I just removed and added it again today

"react-native-modal": "^13.0.1",

Also I know that setTimeout is a workaround but it causes some bugs in my actual use case and not this simplified version. Any help would be truly appreciated and thanks ahead of time.

Javascript detection of browser focus/visibility when mac screenshot tool is used

I’m building a game and I use the keypress events to detect certain keys being used. Basically updating a boolean flag via addEventListener for keydown and keyup. Works great.

However, I use the “shift” key for a certain powerup in the game. And when users try and take screen recordings via Mac screenshot tool (CTRL+SHIFT+4 or CTRL+SHIFT+5) the shift key causes the power up to get triggered.

It’s a mild annoyance, but I’ve been trying to detect it when this happens via
tracking document.visibilityState and document.hasFocus(). But neither of them change when the user presses this keyboard combination of Mac.

Is there a way to detect this via Javascript so I can clear the keyup event for the Shift input when it happens?

In Angular ViewChild it’s possible to use multiselectors using a directive and a id name?

I want to select a component using a Directive and a id name. Is this possible ? I mean I know we can use multi selectors like this:

@ViewChild('whatever1,whatever2,etc') iMaskList: IMaskDirective<IMask.MaskedNumber>;

and I can select using a directive, like this:

@ViewChild(IMaskDirective) iMaskList: IMaskDirective<IMask.MaskedNumber>;

but how I do this ?

@ViewChild(IMaskDirective, 'whatever1,whatever2,etc') iMaskList: IMaskDirective<IMask.MaskedNumber>;

I want this because I have 2 inputs IMaskDirective and I want to be able to select one that has a specific id.

I know I can do like:

@ViewChildren(IMaskDirective) iMaskList: QueryList<IMaskDirective<IMask.MaskedNumber>>;

then

this.iMaskList.first.whatever() 

or

this.iMaskList.forEach(e=>e.whatever())

But the problem is that the function I’m calling doesn’t do nothing when I use ViewChildren. So I’m trying to access one component only specifying id as this worked in other components that have only one IMask object.

Module parse failed: Identifier directly after number when using retext-emoji

I don’t know how to fix this. I ony import emoji from ‘retext-emoji’ and some errors display below:

./node_modules/retext-emoji/index.js 25:17
Module parse failed: Identifier directly after number (25:17)
File was processed with these loaders:
 * ./node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| import { gemoji } from 'gemoji';
| const own = {}.hasOwnProperty;
> const vs16 = 0xfe_0f;
| /** @type {Record<string, gemoji[number]>} */
|

concatenate nested array property of an object

I have a JSONLines file containing thousands of items and I need to merge all of them but for arrays instead of merge need to concatenate them. I don’t have the item schema so need to dynamically do this.

{title: 'test', data: [1]}
{title: 'test', data: [2]}
{title: 'test1', data: [3]}

and output will be something like this

{title: 'test1', data: [1,2,3]}

not sure what is the best performing way I can do.

Use Single button to toggle two functions

I have a code that allows me to easily switch from light mode to dark mode without having to write css for dark mode, it works with two buttons, each executing either the light mode or dark mode depending on your choice of click. However i want to merge this two functions into one single button so that it can be used to toggle the function. If anyone answering does include how it can be used with a toggle button, that won’t be bad at all… The code i am using is

const htmlEl = document.getElementsByTagName('html')[0];

const toggleTheme = (theme) => {
    htmlEl.dataset.theme = theme;
}
html {
    transition: color 300ms, background-color 300ms !important;
}

html[data-theme='dark'] {
    background: #000;
    filter: invert(1) hue-rotate(180deg)
}

html[data-theme='dark'] img {
  filter: invert(1) hue-rotate(180deg)
}
<button onclick="toggleTheme('dark');">Dark Mode Test</button>
    
<button onclick="toggleTheme('light');">Light Mode Test</button>

<br><font color="red">WE ARE RED</font>
<br><font color="blue">WE ARE BLUE</font>
<br><font color="black">WE ARE Black</font>

Then i tried to execute the switch using Eventlisteners this way

<script>
   var btn = document.getElementById('navbtn');

btn.addEventListener('click', function() {
  var foo = 'dark';
 
    if (foo === "light") {
        toggleTheme('dark');
    } else {
        toggleTheme('light');
    }

}, false);
</script>

This however only reacts on first click and not on second. What could be the best way to achieve this? Thanks in anticipation.

Replace null values with empty strings in API response

I run a JS API request as below:

const options = {
  url: `https://${bundle.authData.server}.boostlingo.com/api/web/profile/read-only-form/${bundle.inputData.interpreterId}`,
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': `Bearer ${bundle.authData.token}`
  },
  params: {

  }
}

return z.request(options)
  .then((response) => {
    response.throwForStatus();
    const results = response.json;

    // You can do any parsing you need for results here before returning them

    return results;
  });

And the response is an array that looks like this:

{
    "fieldPolicyId": 4,
    "fields": [
        {
            "fieldId": 21,
            "fieldTypeId": 2,
            "fieldFormatTypeId": 3,
            "includeInPrintView": false,
            "label": "Note (visible to LSP only)",
            "errorMessage": null,
            "description": "Here PMs can add additional notes to Interpreter profiles. Such notes remain hidden from Interpreter view",
            "value": null
        },
        {
            "fieldId": 2,
            "fieldTypeId": 1,
            "fieldFormatTypeId": 3,
            "includeInPrintView": false,
            "label": "NAATI CPN No",
            "errorMessage": null,
            "description": "Unique NAATI identification number",
            "value": "CPN6FZ66L"
        },
        {
            "fieldId": 233,
            "fieldTypeId": 1,
            "fieldFormatTypeId": 3,
            "includeInPrintView": false,
            "label": "NAATI No",
            "errorMessage": null,
            "description": "NAATI No if only accredited and CPN not available",
            "value": null
        },
        {
            "fieldId": 150,
            "fieldTypeId": 1,
            "fieldFormatTypeId": 3,
            "includeInPrintView": false,
            "label": "NAATI Certification expires on (DD-MM-YYYY):",
            "errorMessage": null,
            "description": "(DD-MM-YYYY)",
            "value": null
        },
        {
            "fieldId": 3,
            "fieldTypeId": 5,
            "fieldFormatTypeId": 3,
            "includeInPrintView": false,
            "label": "NAATI Interpreter certification level",
            "errorMessage": null,
            "description": "Select level of certification for interpreting",
            "value": "Certified Interpreter"
        },

While this is a bit unconventional, I need to replace the “null” values by empty strings “”.

Any idea how to modify the request to achieve this? Otherwise, the null values mess up with the rest of my application.

Thank you

creating s in JS

I’m working on some code to create lists based on the time of the day… this would be a really easy thing to just add in HTML, but I’m trying this method for some future-proofing, and to see if I can get it to work. I’ve looked at several pages on w3, MDN, and right here on StackOverflow, and this is what I’ve put together, but I can’t seem to get it to run properly.

I should also say, I’m really new to programming and this is my first project. I’ve been slowly building it as I learn new concepts as a way to put them into practice.

Thanks for any help you can offer!

morningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];
eveningMedsList = ['med1', 'med2', 'med3', 'med4', 'med5'];

const hour = new Date().getHours();

function listMeds() {
    if (hour >= 19 && hour <= 22) {
        let eveningMeds = document.getElementById('evening-meds-list');
            eveMed = document.createElement('li');
            eveningMedsList.forEach(function (med, index) {
                clone = eveMed.cloneNode();
                clone.textContent = (index +1) + ': ' + med;
                eveningMeds.appendChild(clone);
            });
    }
}

listMeds();
<div id="reminders-pics-container">
                        <div id="pics-box-morning">
                            <p>Morning meds pic</p>
                            <ul id="morning-meds-list">
                            </ul>
                        </div>
                        <div id="pics-box-lunch">
                            <p>Lunch meds pic</p>
                        </div>
                        <div id="pics-box-dinner">
                            <p>Dinner meds pic</p>
                        </div>
                        <div id="pics-box-evening">
                            <p> Evening meds pic</p>
                            <ul id="evening-meds-list">  
                            </ul>
                        </div>
                        <div id="pics-box-blank">
                            <p>No meds</p>
                        </div>
                    </div>