finding the bank account closest to but not zero ‘0’ [duplicate]

I’m doing for-loop practice and I can’t seem to find out how to exit the loop when the iteration goes over the lowest value that’s not zero, the loop continues and returns the last value in the array of bank account balances.
Original question:
Return an array with a bank account object with the lowest balance but not broke ( balance > 0 )
In case there is no account that has balance > 0 return an empty array.

const bankAccounts = [
  {
    id: 1,
    name: "Susan",
    balance: 100.32,
    deposits: [150, 30, 221],
    withdrawals: [110, 70.68, 120],
  },
  { id: 2, name: "Morgan", balance: 3.0, deposits: [1100] },
  {
    id: 3,
    name: "Joshua",
    balance: 18456.57,
    deposits: [4000, 5000, 6000, 9200, 256.57],
    withdrawals: [1500, 1400, 1500, 1500],
  },
  { id: 4, name: "Candy", balance: 1.0 },
  { id: 5, name: "Phil", balance: 18.0, deposits: [100, 18], withdrawals: [100] },
];


function itsSomething(array){
let min = [];
  for (let i = 0; i < array.length; i++){
    if (array[i].balance > 0){
    if (array[0].balance>array[i].balance){
      min = array[i]
    }
    }else{
      min =[]
    }
  }
  
   return min
}
console.log(itsSomething(bankAccounts))

the output should be

[ id: 4, name: "Candy", balance: 1.0 ]

Jquery parallax multiple elements – movement in x direction only

Trying to create a parallax effect where the x position changes between two layers. I am unsure how to recreate this smoothly and maybe with easing to keep things feeling fluid.

How could you enhance the formula in the function to work better, also is the focus correct or should the position of the mouse be determined more on the body.

enter image description here

$( document ).ready(function() {


var myElement2= $(".hero-section-text-holder");
var myElement = $(".hero-text-blur");

function setTranslate(xPos, yPos, zPos, el) {
  console.log("test");
  el.style.transform = `translate3d(${xPos}, 0, 0) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg)`;
}


myElement.mousemove(function(event) {
  console.log("mousemoveY---", event.clientX, event.clientY);

  let x = event.clientX;

  var position = {
    left: myElement[0].offsetLeft
  };

  console.log("x", x);

  console.log("position", position);

  let degx = position.left - x;

  console.log("degx", degx);

  setTranslate(-(degx / 20)+"px" , 0, 0, myElement[0]);
  
  
 setTranslate((degx / 10)+"px", 0, 0, myElement2[0]);
});


myElement.mouseleave(function() {
  console.log("mouseleave");
  setTranslate(0, 0, 0, myElement[0]);
  setTranslate(0, 0, 0, myElement2[0]);
});

});
body {
    color: #fff;
    background-color: #000;
    font-family: Manrope, sans-serif;
    font-size: 14px;
    line-height: 1.2;
}


.container {
  padding: 40px;
}

img {
    max-width: 100%;
    vertical-align: middle;
    display: inline-block;
}



.hero-section {
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    display: flex;
}

.hero-section-text-holder {
    width: 100%;
    height: 130vh;
    flex-direction: column;
    align-items: center;
    display: flex;
}


.hero-section-sticky {
    width: 100%;
    position: -webkit-sticky;
    position: sticky;
    top: 50%;
}


.hero-sticky-holder {
    width: 100%;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    display: flex;
}


.hero-text-holder {
    grid-column-gap: 60px;
    perspective: 1000px;
    white-space: nowrap;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    display: flex;
    position: absolute;
}

.hero-text-wrapper {
    justify-content: center;
    align-items: center;
    display: flex;
}


.hero-text {
    -webkit-text-fill-color: transparent;
    background-image: linear-gradient(to right, #eec5bd, #f3b1a5 35%, #c6caf6 72%, #dad9e9);
    -webkit-background-clip: text;
    background-clip: text;
    font-size: 14vw;
    font-weight: 800;
}

.hero-text-blur {
    opacity: .64;
    filter: blur(120px);
    -webkit-text-fill-color: transparent;
    background-image: linear-gradient(to right, #eec5bd, #f3b1a5 35%, #c6caf6 72%, #dad9e9);
    -webkit-background-clip: text;
    background-clip: text;
    font-size: 14vw;
    font-weight: 800;
    position: absolute;
}


.hero-text._02 {
    background-image: linear-gradient(to right, #eec5bd, #f3b1a5 6%, #c6caf6 61%, #dad9e9 72%);
}


.iphone-holder {
    z-index: 1;
    height: 600px;
    border-radius: 60px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    display: flex;
    position: relative;
    top: 6%;
}

.iphone-holder{
      transform: translate3d(0px, 0%, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg);
    transform-style: preserve-3d;
    opacity: 1;  
}





.iphone-screen {
    z-index: 1;
    flex-direction: column;
    justify-content: flex-start;
    align-items: center;
    padding: 4.1% 4.6%;
    display: flex;
    position: absolute;
    top: 0%;
    bottom: 0%;
    left: 0%;
    right: 0%;
}

.iphone-screen-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: 50% 0%;
    border-radius: 25px;
}

.iphone-image {
    z-index: 2;
    height: 100%;
    position: relative;
}

.iphone-drop-shadow {
    width: 120%;
    height: 70%;
    filter: blur(64px);
    background-color: #000;
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="container">

  <div class="hero-section">
    <div class="hero-section-text-holder" style="will-change: transform; transform: translate3d(-6.72px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d;">
      <div class="hero-section-sticky">
        <div class="hero-sticky-holder">
          <div class="hero-text-holder" style="will-change: transform; transform: translate3d(13.44px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d;">
            <div class="hero-text-wrapper _01" style="transform: translate3d(0px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d; opacity: 1;">
              <div class="hero-text">Test1</div>
              <div class="hero-text-blur" style="opacity: 0.6; filter: blur(120px); will-change: transform; transform: translate3d(-33.6px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d;">Test1</div>
            </div>
            <div class="hero-text-wrapper _02" style="transform: translate3d(0px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d; opacity: 1;">
              <div class="hero-text _02">Test2</div>
              <div class="hero-text-blur" style="opacity: 0.6; filter: blur(120px); will-change: transform; transform: translate3d(-33.6px, 0px, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d;">Test2</div>
            </div>
          </div>
        </div>
      </div>
      <div class="iphone-holder" style="transform: translate3d(0px, 0%, 0px) scale3d(1, 1, 1) rotateX(0deg) rotateY(0deg) rotateZ(0deg) skew(0deg, 0deg); transform-style: preserve-3d; opacity: 1;"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63aefb47917c0cfa0943fc97_iPhone%2014%20Pro%20%E2%80%93%20Space%20Black.webp" loading="lazy" sizes="(max-width: 767px) 196.6796875px, 295.015625px" srcset="https://assets.website-files.com/63aee5793ca698452efe7f60/63aefb47917c0cfa0943fc97_iPhone%2014%20Pro%20%E2%80%93%20Space%20Black-p-500.webp 500w, https://assets.website-files.com/63aee5793ca698452efe7f60/63aefb47917c0cfa0943fc97_iPhone%2014%20Pro%20%E2%80%93%20Space%20Black.webp 800w" alt="" class="iphone-image">
        <div class="iphone-screen"><img src="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63aefd2632bfdbf4073fa431_Hero%20Iphone%20Image.webp" loading="lazy" alt="" sizes="(max-width: 479px) 80vw, 267.875px" srcset="https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63aefd2632bfdbf4073fa431_Hero%20Iphone%20Image-p-500.webp 500w, https://cdn.prod.website-files.com/63aee5793ca698452efe7f60/63aefd2632bfdbf4073fa431_Hero%20Iphone%20Image.webp 729w" class="iphone-screen-image"></div>
        <div class="iphone-drop-shadow" style="opacity: 1;"></div>
      </div>
    </div>
  </div>


</div>

Laravel get table data from local server and store it back on online server

I am trying to get collection from my local database (order)table and store it to online database (order) table. Basically what I am doing now is

  1. get all the order table data from local database and send it as order variable to blade
  2. send back order variable to online database using ajax
  3. store the order variable to online database (order) table

This last point (3) is where I am having an issue.

Here is how I get the data from the local database:

$orders = DB::table("orders")->where('created_at', '>', Carbon::now()->subHours(15))->latest()->get()->toArray();
     return $orders;

And this is the order variable I get on the blade:

[{"id":11,"drinkName":"Power Horse","drinkId":"19","drinkType":"Energy Drink","costPerDrink":"5000","totalOrdered":"8","totalOrderAmount":"40000","discount":null,"transactionId":null,"status":"Initiated","waitressName":"Jane","waitressId":"3","created_at":"2024-08-27 14:52:56","updated_at":"2024-08-27 14:52:56"},id":10,"drinkName":"Coke","drinkId":"9","drinkType":"Chasers","costPerDrink":"1000","totalOrdered":"3","totalOrderAmount":"3000","discount":null,"transactionId":null,"status":"Initiated","waitressName":"Jane","waitressId":"3","created_at":"2024-08-27 14:52:49","updated_at":"2024-08-27 14:52:49"},{"id":9,"drinkName":"Crystal","drinkId":"1","drinkType":"Champagne","costPerDrink":"800000","totalOrdered":"3","totalOrderAmount":"2400000","discount":null,"transactionId":null,"status":"Initiated","waitressName":"Jane","waitressId":"3","created_at":"2024-08-27 14:52:41","updated_at":"2024-08-27 14:52:41"}]

This is how I send it to the online server:

function oneSecondFunction(){ 
  $.ajax({
    type:'POST', 
    url:"mysite/app/api/testItem",
    data:{orders : orders, _token: "<?php echo csrf_token(); ?>" },
    success:function(data){                     
      console.log(data);                     
    }
    }); 
}

What I get at the online server:

[{&quot;id&quot;:11,&quot;drinkName&quot;:&quot;Power Horse&quot;,&quot;drinkId&quot;:&quot;19&quot;,&quot;drinkType&quot;:&quot;Energy Drink&quot;,&quot;costPerDrink&quot;:&quot;5000&quot;,&quot;totalOrdered&quot;:&quot;8&quot;,&quot;totalOrderAmount&quot;:&quot;40000&quot;,&quot;discount&quot;:null,&quot;transactionId&quot;:null,&quot;status&quot;:&quot;Initiated&quot;,&quot;waitressName&quot;:&quot;Jane&quot;,&quot;waitressId&quot;:&quot;3&quot;,&quot;created_at&quot;:&quot;2024-08-27 14:52:56&quot;,&quot;updated_at&quot;:&quot;2024-08-27 14:52:56&quot;},{&quot;id&quot;:10,&quot;drinkName&quot;:&quot;Coke&quot;,&quot;drinkId&quot;:&quot;9&quot;,&quot;drinkType&quot;:&quot;Chasers&quot;,&quot;costPerDrink&quot;:&quot;1000&quot;,&quot;totalOrdered&quot;:&quot;3&quot;,&quot;totalOrderAmount&quot;:&quot;3000&quot;,&quot;discount&quot;:null,&quot;transactionId&quot;:null,&quot;status&quot;:&quot;Initiated&quot;,&quot;waitressName&quot;:&quot;Jane&quot;,&quot;waitressId&quot;:&quot;3&quot;,&quot;created_at&quot;:&quot;2024-08-27 14:52:49&quot;,&quot;updated_at&quot;:&quot;2024-08-27 14:52:49&quot;},{&quot;id&quot;:9,&quot;drinkName&quot;:&quot;Crystal&quot;,&quot;drinkId&quot;:&quot;1&quot;,&quot;drinkType&quot;:&quot;Champagne&quot;,&quot;costPerDrink&quot;:&quot;800000&quot;,&quot;totalOrdered&quot;:&quot;3&quot;,&quot;totalOrderAmount&quot;:&quot;2400000&quot;,&quot;discount&quot;:null,&quot;transactionId&quot;:null,&quot;status&quot;:&quot;Initiated&quot;,&quot;waitressName&quot;:&quot;Jane&quot;,&quot;waitressId&quot;:&quot;3&quot;,&quot;created_at&quot;:&quot;2024-08-27 14:52:41&quot;,&quot;updated_at&quot;:&quot;2024-08-27 14:52:41&quot;}] 

How can I store this at the online order table? any code samples and guidance are welcomed.

Why does my XMLHttpRequest cancel my background task before reloading the page

I’m trying to send a XMLHttpRequest to my backend if a user chooses to reload the webpage while a task is running on the backend. It is to function like this:

  1. The user starts the task(translation).
  2. If the user decides to reload the page or navigate away they should get an alert that the task will stop if they navigate away. If they still choose to navigate away the request is sent to a stop_task view on the backend.

However, currently if the user starts to navigate away or reloads the task is terminated once the alert shows instead of after the user confirms that they still want to reload/navigate away.

Here is my code
JS:

wwindow.addEventListener('beforeunload', function (e) {
    if (isTranslating) {
        stopTranslation();
        e.preventDefault();
        e.returnValue = '';
        return 'Translation in progress. Are you sure you want to leave?';
    }
});

function stopTranslaion() {
    if (isTranslating && currentTaskId) {
        // Cancel the polling
        console.log(currentTaskId)
        clearInterval(pollInterval);
        
        // Send a request to the server to stop the task
        const xhr = new XMLHttpRequest();
        xhr.onload = function() {
            if (xhr.status == 200) {
                const response = JSON.parse(xhr.responseText);
                if (response.status === 'stopped') {
                    console.log('Translation stopped');
                    isTranslating = false;
                    currentTaskId = null;
                    // Update UI to reflect stopped state
                    showTranslationStopped();
                }
            } else {
                console.error('Failed to stop translation');
            }
        };
        xhr.onerror = function() {
            console.error('Connection error while trying to stop translation');
        };
        xhr.open('POST', `/translate/stop_task/${currentTaskId}/`, true);
        xhr.setRequestHeader('X-CSRFToken', getCsrfToken()); 
        xhr.send();
    }
}
function showTranslationStopped() {
    // Update UI to show that translation has been stopped
    translatingFileField.style.display = 'none';
    const stoppedMessage = document.createElement('div');
    stoppedMessage.textContent = 'Translation has been stopped.';
    form.appendChild(stoppedMessage);
}

views.py:

@csrf_protect
def stop_task(request, task_id):
    if request.method == 'POST':
        try:
            # Revoke the Celery task
            app.control.revoke(task_id, terminate=True)
            
            return JsonResponse({'status': 'stopped'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)   
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)

I would prefer for it to function as detailed in steps 1 and 2.
My tasks are handled using Celery with redis

Javascript – Delay UI events until promisse finishes

I am porting an application to the web. All client logic already exists, and is executed on server side.

So, I have the following behavior: An Form with 3 fields (Name, Ammount and Value, for example), and a button to Save.

When pressing Ctrl+S, the ‘Save’ button is triggered, all 3 fields are cleared and the focus goes to the first field.

The user does not want to wait for the server finish the promisse of the save button, to start the input of the next item. So, he start typing while still processing the save button, and those keys are lost, or placed on the other form fields.

I need to somehow hold the user input, and, after the Save logic is done, release the events.

So far, I prototyped with the following approaches:

  • Transform all Promises into sync methods. This way works, but chrome gives an warning saying XMLHttpRequest on the main thread is deprecated.
  • Manually catch the UI events and manually handling them once the promisse is fullfiled. This also works, but there are several issues, like handling Ctrl+C,V and others, and is far
    more complex…

I am not happy with any of this options, so asking here about any other possible approaches?

Tone.js + React: Why is this simple repeating synth sequence not working as I expect?

This is a play/stop button that, when pressed, plays a given number of random notes, waits, and then plays another sequence of random notes. It continues until you press stop. You can also select how many notes are in the sequence.

But it’s being unexpected in a few ways. Most obviously:

  • Sometimes the pause between sequences is really long (10-20 seconds instead of a few seconds)
  • When you adjust the counter, it doesn’t seem to follow what you selected.

Am I using Tone.js properly? I’m not too familiar with AudioContexts, transforms, and the different Tone.js methods, but I seem to have it working.

Here is a codesandbox, but let me know if I can improve this question.

https://codesandbox.io/p/sandbox/keen-ellis-y79svm

Errors raised in the BodyParser middleware not propagated to interceptor

I have a NestJS application that is using the expressbuilt-in BodyParser middleware to limit the request size. I’ve created a global interceptor to transform various errors and exceptions, and have also created a global ErrorFilter to cleanup and create responses.

// middleware code:
nestApp.use('*', json({ limit: '256kb' }))

The above code is called in the bootstrap method of the application.

I also have an ErrorInteceptor that is registered before the app is intialized

// interceptor code
export class ErrorInterceptor implements NestInterceptor {
  intercept(_context: ExecutionContext, next: CallHandler): Observable<unknown> {
    return next.handle().pipe(
      catchError(error => {
        // ... do error transformations
      }),
    )
  }
}

Lastly I also register a global custom ErrorFilter.

Whenever an error is throw in the applicative code it will go through both the interceptor and the error filter. However, errors thrown by the built-in middleware are only passed to the error filter i.e. a PayloadTooLarge error won’t be passed to the interceptor to transform. It will go directly to the filter.

According to the docs, interceptors are called after the middleware and before the filters so I don’t understand what’s going on. My guess is that since I’m using a 4.x express version something isn’t handled properly but I can’t upgrade to 5.x. The docs say that:

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. For example:

I want to avoid from adding a custom error handler to the middleware since I want everything transformed by the interceptor. Any help or hints are greatly appreciated!

A gaming company is working on a platformer game. They need a function that will compute the character’s final speed, given a map and a starting [closed]

Link to the question

enter image description here

i am trying to solve this problem in javascript.

if given this calculateFinalSpeed(60, [0, 30, 0, -45, 0]) it should print 75

this is what i tried in java

public class GamePlatform {

    public static double calculateFinalSpeed(double initialSpeed, int[] inclinations) {
        double currentSpeed = initialSpeed;

        for (int angle : inclinations) {
            if (angle > 0) {
                // Uphill: Reduce speed
                currentSpeed *= (1 - angle / 100.0);
            } else {
                // Downhill: Increase speed
                currentSpeed *= (1 + Math.abs(angle) / 100.0);
            }

            // If the speed drops to 0 or below, the character loses
            if (currentSpeed <= 0) {
                return 0;
            }
        }

        return currentSpeed;
    }

    public static void main(String[] args) {
        System.out.println(calculateFinalSpeed(60.0, new int[] { 0, 30, 0, -45, 0 })); // Expected output: 75.0
    }
}

but it is also failing !

How to migrate script tag to a modern vite app

I created my resume on https://dev.sambarnades.com using a Bootstrap model.

Now, i would want to re-adapt that website and power it on Netlify with Sanity as headless CMS in order to easily & visually modify it through Netlify.

I created a react-vite app thanks to :

npm create vite@latest

Then, I copied & past the content, adapting it to .jsx format.

But it seems the former script tags aren’t read by this new vite app format.


index.html (where is pointing the React app.jsx)

 <body class="index-page">
    <main id="root"></main>

    <!-- Vendor JS Files -->
    <script src="src/assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script> 
    <script src="src/assets/vendor/aos/aos.js"></script>
    <script src="src/assets/vendor/typed.js/typed.umd.js"></script>
    <script src="src/assets/vendor/purecounter/purecounter_vanilla.js"></script>
    <script src="src/assets/vendor/waypoints/noframework.waypoints.js"></script>
    <script src="src/assets/vendor/glightbox/js/glightbox.min.js"></script>
    <script src="src/assets/vendor/imagesloaded/imagesloaded.pkgd.min.js"></script>
    <script src="src/assets/vendor/isotope-layout/isotope.pkgd.min.js"></script>
    <script src="src/assets/vendor/swiper/swiper-bundle.min.js"></script>

    <!-- Main JS File -->
    <script src="src/assets/js/template.js"></script>

    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

app.jsx (where I copied my content.)

function App() {

  return (
    <>
      <header id='header' className='header d-flex flex-column justify-content-center'>

        <i className='header-toggle d-xl-none bi bi-list'></i>

... all the code ...

 </div>
      </div>
    </footer>
  <a href="#" id="scroll-top" className="scroll-top d-flex align-items-center justify-content-center"><i className="bi bi-arrow-up-short"></i></a>
    </>
  )
}

export default App

I should see the exact same content as on https://dev.sambarnades.com but instead of it, I only see this picture & blank content. It seems that all the content which is driven by the <script> tags is not interpreted.

enter image description here

I will be very glad to have ideas & advice about this issue. Thanks!

Why cant I change the position of the canvas tag in my html file? [duplicate]

I want to center the canvas

<!DOCTYPE html>
<html>
<head>
    <script>
        function init() {
            console.log("Hello world!");
            draw();
        }

        function draw() {
            var myCanv = document.getElementById("can");
            const rctngl = myCanv.getContext("2d");

            rctngl.fillStyle = "yellow";
            rctngl.strokeRect(19, 19, 42, 42);
            rctngl.fillRect(20, 20, 40, 40);
        }

    </script>
</head>

<body onload="init()">

<h1 style="text-align: center">Basic Partical System</h1>
    <br />
    <br />

    <canvas id="can" width="300" height="200" style="border:1px solid gray" >

    </canvas>

    <br />

     <button type="button">Change Spawn Color</button>

    <br />
    <p>
        Frame Count: 0
    </p>
    <p>
        Rectangle Count: 0
    </p>
    


</body>
</html>

I am have no idea where I am making a mistake. or if canvas can even be moved. Any help would be appreciated

after trying these in the canvas tag:
position: relative;
position: center;
margin-left: auto;
margin-left: 100px;

Nothing has changed and it stays on the left of the page and will not move at all.

Add up JSON strings to one variable | JavaScript

I have been trying to figure out how to merge several JSON strings into one.

My method is this:
if (observations[31]) { // Ignore this. document.getElementById("ajaxrainmo").textContent = observations[31].imperial.precipTotal + observations[30].imperial.precipTotal + observations[29].imperial.precipTotal + observations[28].imperial.precipTotal + observations[27].imperial.precipTotal + observations[26].imperial.precipTotal + observations[25].imperial.precipTotal + observations[24].imperial.precipTotal + observations[23].imperial.precipTotal + observations[22].imperial.precipTotal + observations[21].imperial.precipTotal + observations[20].imperial.precipTotal + observations[19].imperial.precipTotal + observations[18].imperial.precipTotal + observations[17].imperial.precipTotal + observations[16].imperial.precipTotal + observations[15].imperial.precipTotal + observations[14].imperial.precipTotal + observations[13].imperial.precipTotal + observations[12].imperial.precipTotal + observations[13].imperial.precipTotal + observations[11].imperial.precipTotal + observations[10].imperial.precipTotal + observations[9].imperial.precipTotal + observations[8].imperial.precipTotal + observations[7].imperial.precipTotal + observations[6].imperial.precipTotal + observations[5].imperial.precipTotal + observations[4].imperial.precipTotal + observations[3].imperial.precipTotal + observations[2].imperial.precipTotal + observations[1].imperial.precipTotal + observations[0].imperial.precipTotal + " in" } // Adding up a bunch of rain totals to one number.

It works.. but it is very confusing and messy.. if there is a faster option avaliable, I could use it. Thanks.

Importing a module created from string in Node.js using URL.createObjectURL

I want to evaluate string as a module and get this module’s exports. I used to do it before in browser environment, but now somewhy I cannot use the same method in node.js

What I tried:

const virtualUrl = URL.createObjectURL(new Blob(['export default 123'], { type: 'text/javascript' }));

import(virtualUrl).then(module => {
    console.log(module.default);
});

This code works as it supposed to in browser, but node says something like

Error: Cannot find module 'blob:null/b8b19c51-4e01-4dda-8fe6-2b6c9517f767'

Why does this happen, where is my url? And how can I get my string module imported?

Socket IO Node JS server-side functions running multiple times on client emit

First off, I have browsed StackOverflow and read multiple threads about this, but couldn’t find the answer.

The problem: Sometimes, when a user clicks a button and thereby emits a message to the server, the server seems to receive that message multiple times and therefore calls a functions multiple times. This way, when a user submits the allInventionsForm (see below) more than 1 point is awarded to a player sometimes.

I hope there’s an internet hero out here who can help me solve the issue!

Client-side code:

allInventionsForm.on("submit", (e) => {
    e.preventDefault()
    const selectedPlayerId = $("input[name='invention']:checked").val()

    // Prevent submitting if nothing selected
    if (!selectedPlayerId) return

    allInventionsForm.hide()


    socket.emit("awardPoint", selectedPlayerId)
    socket.emit("newRound")
  })

Server-side code:

o.on('connection', connected)


function connected(socket) {
  // console.log(Socket ${socket.id} has connected to the server.)

  /* CLIENT EVENT HANDLERS */
  socket.on("joinRoom", () => { joinRoom(socket) })
  [...]
  socket.on("awardPoint", playerId => { awardPoint(socket, playerId) })
  socket.on("newRound", () => { newRound(socket.roomId) })
}

function awardPoint(socket, playerId) {
  const room = func.getRoomById(socket.roomId)
  room.players[${playerId}].score++
  func.emitToRoom(room, "updatePlayerInfo", room)
}

[...]