float number divided float number expect wrong number

My problem is a wrong result.
I have a function this function has a distance and a time.
The result I want to achieve is calculating running speed.

function runningPace(distance, time) {
  let result = time.replace(":", ".")
  let fl = parseFloat(result)
  let calc = fl / distance
  let num = calc.toFixed(2) + ''
  if(num.length === 1) {
    num = num + '.00'
  }
  let rep = num.replace('.', ':')
  console.log(distance, time, result, fl, calc, rep, num)
  
  return rep;
}

console.log(runningPace(5, '25:00'))
console.log(runningPace(4.99, '22:32'))

I wrote such a function. Sorry for the naming, I’ll fix it when I get it fixed.

When I test this code, the output is:

expected ‘4:47’ to equal ‘4:30’

‘4:30’ => four minute thirty second

How can I find a solution? Thanks everyone in advance.

Performance advice on calculating rows/columns based on window-resize for a layout grid (virtualization)

Given you have a row width variable of a container, and items populated inside of it, calculating rows/columns based on that within useEffect hooks seems very expensive.

Looking for advice, conceptually on making it more performant.

Say you’re measuring variables of row width (container width), item height and item width.

Calculating the amount of columns that would fit in the container would be Math.floor(rowWidth / itemWidth)

Calculating the column width + the appropriate gap

columnWidth = itemWidth + (rowWidth - (itemWidth * columns)) / columns

Then the row height would be

itemHeight + 100px (any variable)

Now most of this logic, on window-resize would have to be inside of a useEffect so it keeps changing, but like I said, it all feels very expensive. So just curious on how to do it better.

Thank you!

How to return a react component with the for in statement?

I’m trying to iterate over a nested object with the for..in statement an return text component for each object iterated over.

const animals = {
  "cat": Object {
    "number": 0,
  },
  "dog": Object {
    "number": 1,
  }
{ 
      for(let item in animals) {
        for(let property in animals[item]){
          return (
            <Text>{item}</Text>
            <Text>{animals[item][property]}</Text>
          )
      }
    }
}

As you see above, I tried to wrap the function in curly brackets in hopes of using jsx to render the components much like one would do with .map, but I got a slew of errors, so I’m pretty sure this incorrect.

My Linter says Expression expected for the two for(s) and the return ().

I can console.log item, and animals[item][property] so I am confident everything outside the return () is correct.

How would I go about correctly returning the Text elements?

How can I detect if a serviceworker install fails?

My serviceworker is partially generated by gulp, so there’s some chance it ends up with a SyntaxError or TypeError if I’ve made a mistake, and I’d like to be about to detect in my navigator.serviceWorker.register code that this has occurred, and send an error report.

I haven’t figured out how to do this. I figured there’d be some sort of “on fail” event but I haven’t found one. It looks like maybe I’m looking for an SW with a redundant state…

I tried

const newWorker = reg.installing
newWorker.addEventListener('statechange', () => {
  if (newWorker.state == 'redundant') {
    // log error
  }
})

but the condition doesn’t seem to fire. This condition also doesn’t fire:

reg.addEventListener('updatefound', () => {
  if (reg.redundant) {
    // log error
  }
})

I don’t see any examples in the SW tutorials of this, which is surprising since it seems like a sort of basic thing to want to notice and detect.

React paint flash in a simple example (comparison)

In a simple react app (create-next-app) with two counters, ‘paint flash’ utility in Chrome shows a lot of repainting.

function Counter() {
const [val, setVal] = useState(0);

  return (<>
    <p>{val}</p>
    <button onClick={() => { setVal(val + 1) }}>increment</button>
    <button onClick={() => { setVal(val - 1) }}>decrement</button>
  </>)
}

function App() {
  return <>
    <Counter />
    <Counter />
  </>
}

enter image description here

On the other hand, DOM manipulation with JS achieves minimum repaints.

<p id="val0"></p>
<button id="inc0">increment</button>
<button id="dec0">decrement</button>

<p id="val1"></p>
<button id="inc1">increment</button>
<button id="dec1">decrement</button>

<script>
    let v0 = 0;
    let v1 = 0;

    let val0 = document.getElementById("val0")
    let val1 = document.getElementById("val1")
    let inc0 = document.getElementById("inc0")
    let inc1 = document.getElementById("inc1")
    let dec0 = document.getElementById("dec0")
    let dec1 = document.getElementById("dec1")

    val0.innerText = v0;
    val1.innerText = v1;

    inc0.onclick = () => {val0.innerText = ++v0;}
    inc1.onclick = () => {val1.innerText = ++v1;}

    dec0.onclick = () => {val0.innerText = --v0;}
    dec1.onclick = () => {val1.innerText = --v1;}

</script>

export default App

enter image description here

Is there something I can do to remove the repaints or is this React’s core inefficiency? Also, is my intuition to trust Chrome’s ‘paint flash’ more than ‘React dev tools’ correct?

ckeditor5 using the downcastwriter and the upcastwriter to wrap comments

I’m looking to get ckeditor5 to wrap comments around its own tag rather than a p.

In the source view i’m inputting:

<p>
Some text.
</p>
// Here we have some comments
<p>
Some text 2.
</p>

It becomes

<p>
Some text.
</p>
<p>// Here we have some comments</p>
<p>
Some text 2.
</p>

But I want:

<p>
Some text.
</p>
<comment>// Here we have some comments</comment>
<p>
Some text 2.
</p>

Instead.

And upon downcasting it should become the initial version.

How can I do this by customizing upcast and downcast?

How to implement Javascript async/await/promise in both of AsyncStorage and Json.parse?

Everyone, Here is my dirty code.

const parseJson = async value => {
  try{
    const parsedData = await JSON.parse(value);
    console.log('2', parsedData);
    return parsedData;
  }catch(e){}
}

const getAuthStateData = async () => {
  try{
    const storedAuthData = await AsyncStorage.getItem('authState');
    console.log('1', storedAuthData);
    return storedAuthData != null ? parseJson(storedAuthData) : null;
  }catch(e){}
}

useEffect(() => {
  const authStateData = getAuthStateData();
  console.log('3', authStateData);
}, [])

Expected console state order is

1, 2, 3

Real console state order is

3, 1, 2

The authState has too many data. so get it from Asyncstorage (if you are not familiar with it, you can assume it like as localstorage) takes some time, and also parsing it to json takes 500 ms.
so I need to wait all of them. This is basic of javascript concept: async, sync, promise.
Please help me, seniors!

jQuery stopPropagation not stopping click through

I have a panzoom plugin that is working well. When I click on var elem it adds a small div cp_select in the correct location. Then, when I click on that newly created cp_select div, it removes that div. So you can add and remove it accordingly. However, when I click on the cp_select div, it removes it then immediately adds it back in because the click is propagating through. I have tried event.stopPropagation() and event.stopImmediatePropagation() with no luck. Any ideas how to prevent the cp_select firing the map_click(e)?

enter image description here

window.panzoom = panzoom(elem, {
        onClick(e)     {
            map_click(e);
        }
})


function map_click(e) {
    
    $(".map_cont").prepend('<div class="cp_select" style="left:'+calc_x+'px ;top:'+calc_y+'px"></div>');

}


 $('body').on('click', '.cp_select', function(event) {
    
    event.stopImmediatePropagation()
    $(this).remove()
    return false;
    
});

React js adding regular script to react component

I am new to posting questions to stackoverflow. I have a question about React js. Trying to add an old html page with a script I made.

When I take off the comment from the import it breaks the app. Any way to fix this?
Leaving the script commented lets the page load with the css but nothing else.

Here is the code in the component

import './style.css';
// import './script.js';
import { NavBar } from "../Nav";


export function CountDownTimer() {
    
    return (
        <>
        <NavBar />

    <h1>Countdown</h1>
    <h2>Default set to new years 2050</h2>

    

    <div className='calendar'>
        <input type='date' id='Date' />
        <button onclick="changeDate()">Countdown</button>
    </div>
    

    <div className='timer-container' >
        <div>
            <div id='days'></div>
            <span>days</span>
        </div>
        <div>
            <div id='hours'></div>
            <span>hours</span>
        </div>
        <div>
            <div id='minutes'></div>
            <span>minutes</span>
        </div>
        <div>
            <div id='seconds'></div>
            <span>seconds</span>
        </div>
    </div>


    <div className='timer-container' >
        <div>
            <div id='thours'></div>
            <span>Total hours</span>
        </div>
        <div>
            <div id='tminutes'></div>
            <span>Total minutes</span>
        </div>
        <div>
            <div id='tseconds'></div>
            <span>Total seconds</span>
        </div>
    </div>

    

    {/* <script src="script.js"></script> */}

    </>
    );
}

and the script.js

//target date to countdown to
var setDate = new Date('2050-01-01T00:00:00');
console.log('Date set to: ' + setDate);




var currentDate;
function countdown() {
    currentDate = new Date();


    var time = (setDate.getTime() - currentDate.getTime());
    var seconds = Math.floor(time/1000)%60;
    var minutes = Math.floor(time/60/1000 % 60);
    var hours = Math.floor(time/1000/3600 % 24);
    var days = Math.floor(time/3600/24/1000);

    

    // console.log('days, hours, minutes, seconds', days, hours, minutes, seconds);
    document.getElementById("days").innerHTML = days;
    document.getElementById("hours").innerHTML = hours;
    document.getElementById("minutes").innerHTML = minutes;
    document.getElementById("seconds").innerHTML = seconds;

    var totalSeconds = Math.floor(time/1000);
    var totalMinutes = Math.floor(time/60/1000);
    var totalHours = Math.floor(time/1000/3600);

    document.getElementById("tseconds").innerHTML = totalSeconds;
    document.getElementById("tminutes").innerHTML = totalMinutes;
    document.getElementById("thours").innerHTML = totalHours;
}

function changeDate() {
    var newDate = document.getElementById("Date").value;
    console.log("newDate: ", newDate);
    setDate = new Date(newDate+"T00:00:00");
}

countdown();



setInterval(countdown, 1000);


How can I set src and alt attibutes on an image tag using Javascript

Javascript is something that I am learning bit by bit, so please excuse my ignorance…! 😉

I have a list of images in a gallery, and I am creating a modal on a click event. I have managed to collect all of the sources for the images into an array and have then used the forEach method to appended an li and img tag into a parent ul, with all of the sources going into the src attribute.

My problem is I also have an array of alt attributes as well that I also need to set into the same list of images.

I don’t think I can do both attibutes in one forEach loop, and it seems too messy to do a second loop for the alt attributes. There must be a simpler way, it’s just beyond my current undersatnding.

Here is the code I already have below, I was wondering if perhaps I should be looking at a Json object instead rather than this approach?

 $('.gallery-image img').click(function(){
            $('.modal').addClass('show');
            var images = document.getElementsByClassName('aurora-gallery-image');
            var imageSources = [];
            var imageTitles = [];
            for (var i = 0; i < images.length; i++) {
                 imageSources.push(images[i].src);
                 imageTitles.push(images[i].alt);
            }
           imageSources.forEach(imageFunction);
            
            function imageFunction(item){
               $('.image-modal ul').append('<li class="image-modal-item"><img class="modal-content" alt="" src="' + item + '" /><p id="aurora-gallery-image-title">  </p></li>');
            }
           
           
      }); 

reduce array of numbers into object with key and value amount [duplicate]

I have an array of numbers const array = [1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5];

I’m trying to return an object like this {
‘1’: 1,
‘2’: 1,
‘3’: 2,
‘4’: 3,
‘5’: 4
}

This is a code I’m use for now but it did’n calcutale values.
I’ve tried to google but i didn’t find how to solve it.
Please help

const array = [1, 2, 3, 3, 4, 4, 4, 5, 5, 5, 5];
const convertArrayToObject = (array) =>
array.reduce((acc, curr) => ({
...acc, [curr] : curr
}), {});

React select onChange is getting triggered for the second time with old value

I am using React Select to show list of items . On change of item , i want to show a warning based on some flag . If flag is true , Dialog box will be displayed and and confirm of that , I want to allow the change . For every on on change , i am storing the selected item in local state use effect . On click of confirm from dialog box or if flag is false , i am dispatching actions to store them in redux store .

I am having issue when Dialog box is appearing and on click of confirm, item in dropdown is changing , but onChange is getting called again with first value ,Hence dropdown is going back to initial value .

Why is onChange getting called twice .

Tried event.preventDefault , but not working.

const [name, setName] = React.useState();

const changeValue = (event,selectedItem) => {
    event.preventDefault()
    setName(selectedItem) // storing in UseState hook 
    if(flag){
        props.toggleWarningDialog(true);
    }
    else {
        props.onChangeItem(selectedItem);
    }
}

const handleConfirmChange = (event) => {
        event.preventDefault()
        props.onChangeItem(name); //getting from useState hook and storing in redux by dispatching an action
 }  

Getting the value of array out of scope of a function [duplicate]

I want to know if there is any way to get the value of ref inside an async function.
the code below show the example for my problem:

var results =ref([])
    projectFirestore.collection('patients').where('ssn', '==', '211').onSnapshot((snap) => {
            snap.docs.forEach((doc) => {
              results.value.push(doc.data());
            })  
            
      })
    console.log(results.value.length);  

the output of the console is 0, but if I move the console function inside the function it will print ’21’ (the length of array that retrieved from DB)

is there a way to do a conditional alternative in js

my code is

if(name === 'banana' || name === 'orange') //do something

the word “name” is in my code twice, is there something that I can do to do not repeat it? if I do

if(name === 'banana' || 'orange')

the computer doesn’t understand, maybe there is another way that i dont know yet,

thanks very much