Fastest regex to match all worded numbers (english) from 1 to 99 [closed]

I would like to know if there is a better regex to match all worded numbers from 1 to 99.
With “better” I mean shorter with same performance, OR faster.

I came up with this, I can’t do better.
/b(?<!-)(?:(?:twen(?=ty)|thir|four(?=te)|for(?=ty)|fif|six|seven|eigh|nine)t(?:een|y)(?:(?<=ty)-(?:one|two|three|four|five|six|seven|eight|nine))?|(?:one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve))/

You can test it here: https://regex101.com/r/CYBK5S/1
Javascript if possible.

Reducing an array of objects in JS?

I have fairly symmetrical data I want to reduce:

const data = [
  {
    name: 'Bob',
    relations: {
      siblings: [
        {
          name: 'Tom',
          age: '20'
        },
        {
          name: 'Jacob'
        }
      ]
    }
  },
  {
    name: 'Robert',
    relations: {
      siblings: [
        {
          name: 'Timmy',
          age: '16'
        }
      ]
    }
  }
];

What I’m trying to produce:

const output = {
  name: ['Bob', 'Robert'],
  relations: {
    siblings: {
      name: ['Tom', 'Jacob', 'Timmy'],
      age: ['20', '16']
    }
  }
}

I understand how to do this without recursion, but I wanted a solution that would go deep.
Usually I just use reduce with recursion, but then I realized that I would have to add the value to the current level of the object which I don’t know how to do.

const compact = (value) => {
  if (typeof value === 'string') {
    return { [value]: '' }; // turning into an object for the mean time
  }

  if (Array.isArray(object)) { }

  // if object
  return Object.entries(object).reduce((accum, [key, value]) => {
    // Do I have to pass accum[key] into compact here? Is this the correct way to do this?
    accum[key] = compact(value);
   
    return accum;
  }, {});
};

How can I listen to any variable in React?

In my project, i have a list of schema just like this:

const schema = [
  {
    // some properties...
    label: 'example1',
    effect: {
      depends: [...],
      callback: () => {}
    }
  },
  {
    // some properties...
    label: 'example2',
    effect: {
      depends: [...],
      callback: () => {}
    }
  },
  // for more...
]

Then I will generate the DOM structure based on this schema.

In this schema, when a variable in the depends array is modified, I should execute the callback. However, the elements in depends can be any value, such as an item in props, an observable element from MobX, a value returned from useState, the state of a class component, etc.

So, the implementation of this logic in the code would look something like this:

const getSchema = () => {
  const { propsVal } = props;
  cosnt { mobxVal } = mobxStore;
  const { stateVal } = this.state;
  const normalVal = 1;
  const schema = [
    {
      // some properties...
      label: 'example1',
      effect: {
        depends: [propsVal, stateVal, normalVal],
        callback: (preVal, curVal) => {
          // pre and cur should be objects that contain all the changed properties.
          const { propsVal, stateVal, normalVal } = preVal;
          const { propsVal, stateVal, normalVal } = curVal;
          console.log(preVal)
          console.log(curVal)
        }
      }
    },
    {
      // some properties...
      label: 'example2',
      effect: {
        depends: [mobxVal, stateVal],
        callback: () => {
          // do sth...
        }
      }
    },
    // for more...
  ]
  }
  return schema;
}

So, how should I design it to achieve this functionality?

I previously tried using Proxy, but Proxy intercepts the set operation only if the value is assigned to the object returned by the Proxy. Since these values come from various sources and there isn’t a unified set method, it prevents the Proxy from being able to proxy all values.

I would greatly appreciate any suggestions anyone might have for my question!

SweetAlert2 and Confirm dialog, how to execute action after an jQuery $.ajax call is executed?

I need to reload the page if a $.ajax call was successful (data.error is undefined). I am using jQuery and SweetAlert2 to display the confirmation dialog nicely and this is how my code looks like:

$(function () {
    Swal.fire({
        title: 'Are you sure you want to continue?',
        text: 'Are you sure you want to remove the selected files?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes',
        cancelButtonText: 'No',
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                type: 'POST',
                url: 'http://localhost:8080',
                cache: false,
                dataType: 'json',
                success: function (result) {
                    if (result.error) {
                        // show error message here

                        return false;
                    }

                    location.reload();
                }
            })
        }
    });
})

As you can see I am executing the AJAX request when the user clicks the YES button from the SweetAlert2` confirm dialog.

The AJAX call is being done properly and it does not fail (data.error is undefined). The code should not enter in the if conditional and should reload the page but the reload is not happening and I am not sure what I am missing.

If I execute the AJAX call outside of the SweetAlert2 it works as expected and the page gets reloaded.

Can I get some help? Do you see something weird in my solution?

Motion tracking user-defined area in video

I am looking for a library which handles motion tracking. The user defines an area in the video which he wants to track over several seconds. A perfect example is Adobe After Effects (https://www.youtube.com/watch?v=eyWclmjr94k). I don’t care about object detection (like detecting cat, dog, faces, …) but to actually track the position, scale, rotation of a given area. Does anybody know a library which works in the browser in real-time (or close to real-time)?

I found something like https://trackingjs.com but it looks like it just does object detection or detection of feature points.

Get computed data from multiple children in React parent component

I want to have 2 functional React components:

  • a Data component that holds a value in state, that is passed through props:

  • a SummedValue that also holds a value in state, but calculates this value as the sum of it’s children’s value, where its children can be either Data or other SummedValue components, nested arbitrarily
    I would like to use them like this:

     <SummedValue>               
         <Data value={3}/>
         <Data value={5}/>
     <SummedValue>           
         <Data value={4}/>
         <Data value={1}/>
     </SummedValue>
    

Currently, in the SummedValue component, I can get the data from Data components alone by children.props.value. However I dont know how to get this value from nested SummedValue components, as it is not a prop.

Basically I think this is related to passing data from the child to the parent, but I cant find the configuration that works

function SummedValue({children}) {
// how can I access this computed value in parent component?
let computedValue = 0;

// Only works for props, not internal values
children.forEach(child => {
    if (child.props.value) {
        value += child.props.value
    }
})

return(
    <div>
        <span>SUMMED NUMBER IS: {computedValue}
        {children}
    </div>
)

}

Many thanks for the help 🙂

In React, does creating a click handler outside the JSX have any improvement on performance?

Here is an example of 2 buttons with click handlers, one function is created in the component body, the other in the JSX. Is there any performance differences?

function Parent() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <button onClick={handleClick} />
      <button onClick={() => setCount(count + 1)}>Increment Count</button>
    </div>
  );
}

My understanding is the they are the same, and the function gets recreated on every Parent re-render. But I’m curious if I’m missing anything. I know I can use useCallback or other memoizing techniques, but this question is just purely these 2 scenarios.

rxjs: tap multiple subjects at once

Given two subjects s1 and s2 with subscriptions,

const s1 = new Subject<number>();
const s2 = new Subject<number>();

s1.subscribe({
  next: (value) => console.log("s1 emitted", value),
  complete: () => console.log("s1 completed"),
});

s2.subscribe({
  next: (value) => console.log("s2 emitted", value),
  complete: () => console.log("s2 completed"),
});

and given an observable, say of(1), I could pipe through s1 like so:

of(1).pipe(tap(s1)).subscribe();

which produces the output

s1 emitted 1
s1 completed

But what if you’d like to pipe through s1 AND s2 at once.
Of course I could do something like this:

of(1)
  .pipe(tap((x) => [s1, s2].forEach((s) => of(x).subscribe(s))))
  .subscribe();

which produces the output

s1 emitted 1
s1 completed
s2 emitted 1
s2 completed

But is there a better/shorter way? I tried merge and the lot, but nothing works.

Why isnt my function displaying the table I have created using a for loop to the front end?

I’m trying to create a function that returns the 12 times table of a given number that a user submits through a form. The user inputs a number through an input box and clicks the times button.

Then a 12 times table for that number is listed. I’m having trouble outputting the array from the function to the front end page.

function timestable(x) {
  let x = Number(document.userNum.Number.value);
  let table = [];
  for (i = 0; i++; i < 13) {
    value = x * i;
    table.push(value);
  }
  return table;
};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form name="userNum">
    Number: <input type="text" name="number1">
    <button onclick="timestable()">Times</button>
  </form>
</body>

</html>

Is it possible to optimize this code to get more performance?

I finished programming this type of Penrose Tiling (P1) in javascript / p5.js and the algorithm works very fine and takes 1.549 seconds on a Core i5 – 4590 (3.3 gHz) with 8 GB of RAM to generate the image below. But I would like to know if it’s possible to optimize the code so that there is more performance and takes even less time.

Penrose Tiling - P1

I even asked this when I was starting to program in another post and I used (and optimized) some suggestions made by user Linda Paiste, which was a great suggestion, but I would like to know if it is possible to optimize it further.

Here’s the code:

<html>
  <head>
    <meta charset = "utf-8">
    <title>Penrose Tiling - P1</title>
  </head>
  <body>
  <script src = "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.js"></script>
  <script>

  var size = 10;
  const tolerance = 0.00001;
  const radianFactor = 3.141592653589793 / 180;
  var formVertex = {};
  var mainList = [];
  var forms = [];
  var amount = 0;

  //Each "cyan" pentagon with five rhombus (type 0) will generate two more of the same type forming a "layer" (with the exception of the first). Each time a layer is formed, the quantity is increased until the maximum quantity is reached. You can change the "maxLayerAmount" variable and higher values ​​will produce larger images, but it will take more time.
  var limit = 0;
  var layerAmount = 0;
  var maxLayerAmount = 10;

  var pentagonVertex = [];
  var rhombusVertex = [];
  var boatVextex = [];
  var starVertex = [];

class points
{
  constructor(x, y)
  {
    this.x = x;
    this.y = y;
  }
}

function setup()
{
  let i;
  for (i = 0; i < 5; i++) pentagonVertex[i] = new points();
  for (i = 0; i < 4; i++) rhombusVertex[i] = new points();
  for (i = 0; i < 7; i++) boatVextex[i] = new points();
  for (i = 0; i < 10; i++) starVertex[i] = new points();
  createCanvas(2000, 2000);
}

function createVertexForms(formAngles)
{
  let auxiliar = new Array(formAngles.length);
  let i;
  let previousPoint;
  auxiliar[0] = {x: formVertex.x, y: formVertex.y};
  formAngles.map((formAngles, i) => {
                                    formVertex.angle += formAngles;
                                    previousPoint = auxiliar[i];
                                    auxiliar[i + 1] = {x: previousPoint.x + size * cos(formVertex.angle * radianFactor), y: previousPoint.y + size * (-sin(formVertex.angle * radianFactor))};
                                  });
  return auxiliar;
}

function drawForm(formVertex)
{
  beginShape();
  for (let i in formVertex)
    vertex(formVertex[i].x, formVertex[i].y);
  endShape(CLOSE);
}

function draw()
{
  var startTime = performance.now();
  translate (width / 2, height / 2);
  let startAngle = 18;
  let hipotenuse = size / (2 * sin(36 * radianFactor));
  for (let i = 0; i < 5; i++)
  {
    pentagonVertex[i].x = hipotenuse * cos(startAngle * radianFactor);
    pentagonVertex[i].y = hipotenuse * (-sin(startAngle * radianFactor));
    mainList.unshift({x: pentagonVertex[i].x, y: pentagonVertex[i].y, angle: startAngle - 18, form: 0, type: 1});
    mainList.unshift({x: pentagonVertex[i].x, y: pentagonVertex[i].y, angle: startAngle + 162, form: 2, type: 0});
    startAngle += 72;
  }
  fill('cyan');
  drawForm(pentagonVertex);
  while ((formVertex = mainList.pop()) !== undefined)
  {
    switch (formVertex.form)
    {
      case 0: if (forms.findIndex(item => {return item.identificator === 0 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance);}) >= 0) break;
              rhombusVertex = createVertexForms([0, 36, 144]);
              if (formVertex.type > 1)
              {
                let auxiliar = forms.findIndex(item => {return item.identificator === 0 && item.form.some(form => Math.abs(form.x - rhombusVertex[1].x) < tolerance && Math.abs(form.y - rhombusVertex[1].y) < tolerance)});
                if (auxiliar >= 0)
                {
                  forms.splice(auxiliar, 1);
                  continue;
                }
                  else
                  {
                    auxiliar = forms.findIndex(item => {return item.identificator === 0 && item.form.some(form => Math.abs(form.x - rhombusVertex[3].x) < tolerance && Math.abs(form.y - rhombusVertex[3].y) < tolerance)});
                    if (auxiliar >= 0)
                    {
                      forms.splice(auxiliar, 1);
                      continue;
                    }
                  }
              }
              forms.push({form: rhombusVertex, identificator: 0});
              mainList.unshift({x: rhombusVertex[2].x, y: rhombusVertex[2].y, angle: formVertex.angle + 72, form: 1, type: formVertex.type});
              fill('yellow');
              drawForm(rhombusVertex);
      break;
      case 1: pentagonVertex = createVertexForms([72, 72, 72, 72]);
              if (formVertex.type === 0)
              {
                if (forms.findIndex(item => {return item.identificator === 1 && item.type === 0 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) >= 0) 
                {
                  mainList.unshift({x: pentagonVertex[1].x, y: pentagonVertex[1].y, angle: formVertex.angle + 72, form: 0, type: 1});
                  mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 144, form: 0, type: 1});
                  mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 216, form: 0, type: 1});
                  mainList.unshift({x: pentagonVertex[4].x, y: pentagonVertex[4].y, angle: formVertex.angle + 288, form: 0, type: 1});
                  continue;
                }
                  else
                  {
                    if (amount === limit)
                    {
                      layerAmount++;
                      if (layerAmount > maxLayerAmount)
                      {
                        if (forms.findIndex(item => {return item.identificator === 1 && item.type === 4 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) < 0)
                        {
                          fill('cyan');
                          drawForm(pentagonVertex);
                        }
                          else
                          {
                            mainList.unshift({x: formVertex.x, y: formVertex.y, angle: formVertex.angle - 36, form: 2, type: 3});
                            mainList.unshift({x: pentagonVertex[4].x, y: pentagonVertex[4].y, angle: formVertex.angle + 252, form: 2, type: 3});
                          }
                        forms.push({form: pentagonVertex, identificator: 1, type: 4});
                        break;
                      }
                      amount = 0;
                      limit += 5;
                    }
                    amount++;
                    mainList.unshift({x: pentagonVertex[0].x, y: pentagonVertex[0].y, angle: formVertex.angle + 180, form: 2, type: 0});
                    mainList.unshift({x: pentagonVertex[1].x, y: pentagonVertex[1].y, angle: formVertex.angle + 252, form: 2, type: 0});
                    mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 324, form: 2, type: 0});
                    mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 36, form: 2, type: 0});
                    mainList.unshift({x: pentagonVertex[4].x, y: pentagonVertex[4].y, angle: formVertex.angle + 108, form: 2, type: 0});
                  }
              }
                else if (formVertex.type === 1)
                {
                  mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 144, form: 0, type: 3});
                  mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 216, form: 0, type: 2});
                }
                  else if (formVertex.type === 2)
                  {
                    if ((forms.findIndex(item => {return item.identificator === 1 && item.type === 3 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) >= 0)
                         || (forms.findIndex(item => {return item.identificator === 1 && item.type === 1 && item.form.some(form => Math.abs(form.x - pentagonVertex[1].x) < tolerance && Math.abs(form.y - pentagonVertex[1].y) < tolerance)}) >= 0)) continue;
                    mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 216, form: 0, type: 0});
                  }
                    else
                    {
                      if ((forms.findIndex(item => {return item.identificator === 1 && item.type === 2 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) >= 0)
                           || (forms.findIndex(item => {return item.identificator === 1 && item.type === 1 && item.form.some(form => Math.abs(form.x - pentagonVertex[3].x) < tolerance && Math.abs(form.y - pentagonVertex[3].y) < tolerance)}) >= 0)) continue;
                      mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 144, form: 0, type: 0});
                    }
              forms.push({form: pentagonVertex, identificator: 1, type: formVertex.type});
              fill('cyan');
              drawForm(pentagonVertex);
      break;
      case 2: pentagonVertex = createVertexForms([72, 72, 72, 72]);
              if (formVertex.type < 4)
                if (formVertex.type === 0)
                {
                  mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 108, form: 3, type: 3});
                  mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 252, form: 4, type: 0});
                  mainList.unshift({x: pentagonVertex[4].x, y: pentagonVertex[4].y, angle: formVertex.angle + 108, form: 3, type: 3});
                }
                  else
                  {
                    if (formVertex.type == 3)
                    {
                      if (forms.findIndex(item => {return item.identificator === 5 && item.form.some(form => Math.abs(form.x - pentagonVertex[2].x) < tolerance && Math.abs(form.y - pentagonVertex[2].y) < tolerance)}) < 0) continue;
                      mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle - 36, form: 3, type: 3});
                    }
                    mainList.unshift({x: pentagonVertex[2].x, y: pentagonVertex[2].y, angle: formVertex.angle + 108, form: 3, type: formVertex.type});
                  }
              fill('gray');
              drawForm(pentagonVertex);
      break;
      case 3: pentagonVertex = createVertexForms([72, 72, 72, 72]);
              if (formVertex.type < 3)
                if (formVertex.type === 0) mainList.unshift({x: pentagonVertex[1].x, y: pentagonVertex[1].y, angle: formVertex.angle + 108, form: 5, type: 1});
                  else if (formVertex.type === 1) mainList.unshift({x: formVertex.x, y: formVertex.y, angle: formVertex.angle + 324, form: 4, type: 1});
                    else mainList.unshift({x: pentagonVertex[3].x, y: pentagonVertex[3].y, angle: formVertex.angle + 180, form: 4, type: 1});
              fill('red');
              drawForm(pentagonVertex);
      break;
      case 4: if (formVertex.type === 0)
              {
                if (forms.findIndex(item => {return item.identificator === 5 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) >= 0) continue;
                boatVextex = createVertexForms([-36, -72, 144, 36, 36, 144]);
                mainList.unshift({x: boatVextex[2].x, y: boatVextex[2].y, angle: formVertex.angle + 324, form: 2, type: 1});
                mainList.unshift({x: boatVextex[3].x, y: boatVextex[3].y, angle: formVertex.angle, form: 3, type: 0});
                mainList.unshift({x: boatVextex[5].x, y: boatVextex[5].y, angle: formVertex.angle + 324, form: 2, type: 2});
              }
                else
                {
                  if (forms.findIndex(item => {return item.identificator === 0 && item.form.some(form => Math.abs(form.x - formVertex.x) < tolerance && Math.abs(form.y - formVertex.y) < tolerance)}) >= 0) continue;
                  boatVextex = createVertexForms([36, 144, -72, 144, -72, 144]);
                  mainList.unshift({x: boatVextex[1].x, y: boatVextex[1].y, angle: formVertex.angle + 180, form: 2, type: 4});
                  mainList.unshift({x: boatVextex[2].x, y: boatVextex[2].y, angle: formVertex.angle + 324, form: 3, type: 3});
                  mainList.unshift({x: boatVextex[3].x, y: boatVextex[3].y, angle: formVertex.angle, form: 2, type: 4});
                  mainList.unshift({x: boatVextex[4].x, y: boatVextex[4].y, angle: formVertex.angle + 36, form: 3, type: 3});
                }
              fill('green');
              drawForm(boatVextex);
      break;
      default: if (forms.findIndex(item => {return item.identificator === 5 && item.form.some(form => Math.abs(form.x - (formVertex.x + size * cos((formVertex.angle + 72) * radianFactor))) < tolerance && Math.abs(form.y - (formVertex.y + size * (-sin((formVertex.angle + 72) * radianFactor)))) < tolerance)}) >= 0) continue;
               starVertex = createVertexForms([72, -72, 144, -72, 144, -72, 144, -72, 144]);
               forms.push({form: starVertex, identificator: 5});
               fill('orange');
               drawForm(starVertex);
    }
  }
  var finalTime = performance.now();
  console.log("Time spent: " + ((finalTime - startTime) / 1000) + " seconds.");
  forms.splice(0, forms.length);
  noLoop();
}
  </script>
  </body>
</html>

Send post data from modal form via Post Request in JS

I am writing a signup feature for an application using Node Js and Express js.
This is how I’ve written the form in inside a bootstrap modal views/partials/signUp.

<div class="modal fade" id="signUp" tabindex="-1">
....
    <div class="modal-body">
    <form class="form-signup" id="sign-up-form" action="/views/partials/signUp" method="post">

and this is my post request in server.js

app.post('/signup', function (req,res) {
    const connection = require('./connection');
    const { username, email, dob, password } = req.body;
    const createdAt = new Date().toISOString().slice(0, 19).replace('T', ' ');
    const query = `INSERT INTO user_details (user_name, email, date_of_birth, password, created_at) VALUES ('${username}', '${email}', '${dob}', '${password}', '${createdAt}')`;
    connection.query(query, (err, results) => {
        if (err) throw err;
        res.send('Registration is complete.');
        res.redirect('/');
    });
});

However, req.body was empty / undefined??

Therefore, I realized that there’s something wrong with the way I write form or with how I write post request.

Here’s the routes structure.

enter image description here

Here is the full source for the modal signup page.

views/signUp.ejs

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#signUp">
  Sign Up
</button>

<!-- Modal -->
<div class="modal fade" id="signUp" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Sign Up</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form class="form-signup" id="sign-up-form" action="/views/partials/signUp" method="post">
          <div class="form-floating mb-3">
            <input type="text" id="username" class="form-control" placeholder="Username" required autofocus="" />
            <label for="username">Username</label>
          </div>
          <div class="form-floating">
            <input type="password" id="password" class="form-control" placeholder="Password" required autofocus="" />
            <label for="password">Password</label>
          </div>
          <div class="modal-footer">
            <button class="btn btn-lg btn-primary btn-block" id="signup-submit" type="submit" value="Submit">Sign Up</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

Please let me know if you need any further information.
Appreciate your helps!

Nest js test timers

I have this service in my NestJs application:

 async testTEst(id: string) {
    const user = await this.prismaService.user.findUnique({
      where: {
        id,
      },
    });

    // create 5sec timer
    let seconds = 5;
    const timer = setInterval(() => {
      console.log(`Hello ${user.email}, ${seconds} seconds left`);
      seconds -= 1;
      if (seconds < 0) {
        clearInterval(timer);
      }
    }, 1000);

    return {
      message: 'User will be deleted in 15 seconds',
    };
  }

I created an integration test for this where i test how the service interact with all dependancies and database.

 it('should notify about user deletion countdown', async () => {
      jest.useFakeTimers();

      const u = await prismaService.user.create({
        data: { email: '[email protected]', password: '234' },
      });

      const response = userService.testTEst(u.id);
      jest.advanceTimersByTime(5000);
      const result = await response; // Ensure the async operation is completed

      expect(result).toEqual({
        message: 'User will be deleted in 15 seconds',
      });
    });

Running the test i get: thrown: "Exceeded timeout of 5000 ms for a test..

I tried this: testTimeout: 20000 but it does not work.
I assume that i did something incorrect in my test but i can not find what.
Question: Who faced this issue and how to fix my test?
Note: I am using MACos

Access page specific javascript in rails 7.2

I am using importmap-rails.
I have a common.js file at app/javascript/controllers/center/staff_profiles/common.js

in importmap, i already pinned controllers using below

pin_all_from "app/javascript/controllers", under: "controllers"

In index.html, I am calling common.js like below

<%= content_for :page_specific_scripts do %>
  <%=  javascript_import_module_tag 'controllers/center/staff_profiles/common' %>
<% end %>

I have page_specific_scripts in layouts
Everything is working as expected till this place.

I have another file app/javascript/controllers/shared/scroll.js like below

export function handleScroll(){
--  scroll code
}

and i am calling this in another js file app/javascript/controllers/user/work.js like below

import {handleScroll} from "../../shared/scroll";

document.addEventListener("turbo:load", function() {
    handleScroll();
});

Then I got error in production which says https://myapp.com/assets/controllers/shared/scroll” was blocked because of a disallowed MIME type (“text/html”).

This is working in local env.

I am using Rails 7.2

Yup Dynamic Util Does Not Validate

I am trying to write a custom yup util for my project. my goal here is to make the form fields specified according to the data coming from the backend service conform to a single type or rule (eg. key-value for selectBox). For some reason, the validation I have written for the data sent by the backend in the code I wrote does not work :), it actually freezes as a yup object and the describe method also works, but it does not validate with the value values I give, I have tried different solution methods to solve the problem, but I have not been able to solve the problem. I would like help from you on this issue, if there is something wrong with my code or if you have any ideas, I would be very grateful, thank you in advance.

import * as yup from 'yup';

const defaultValidationRules = (customMessage) => {
  return {
    string: yup
      .string()
      .min(1)
      .required(customMessage ?? `path is required`),
    number: yup.number().required(customMessage ?? `path is required`),
    boolean: yup.boolean().required(customMessage ?? `path is required`),
    object: yup.object().required(customMessage ?? `path is required`),
    array: yup.array().required(customMessage ?? `path is required`)
  };
};

const createValidationSchema = (backendDependencies) => {
  const shape = {};

  if (Array.isArray(backendDependencies)) {
    backendDependencies.forEach((dependency) => {
      const { path, data, rule, customRule, customMessage, objectPathField } = dependency;

      const subShape = {};

      if (Array.isArray(data)) {
        data.forEach((item) => {
          if (customRule) {
            subShape[item[objectPathField]] = customRule;
          } else {
            subShape[item[objectPathField]] = defaultValidationRules(customMessage)[rule];
          }
        });
      } else {
        Object.keys(data).forEach((item) => {
          if (customRule) {
            subShape[item] = customRule;
          } else {
            subShape[item] = defaultValidationRules(customMessage)[rule];
          }
        });
      }

      shape[path] = yup.object().shape(subShape);
    });
  } else {
    const { path, data, rule, customRule, customMessage, objectPathField } = backendDependencies;
    const subShape = {};

    if (Array.isArray(data)) {
      data.forEach((item) => {
        if (customRule) {
          subShape[item[objectPathField]] = customRule;
        } else {
          subShape[item[objectPathField]] = defaultValidationRules(customMessage)[rule];
        }
      });
    } else {
      Object.keys(data).forEach((item) => {
        if (customRule) {
          subShape[item] = customRule;
        } else {
          subShape[item] = defaultValidationRules(customMessage)[rule];
        }
      });
    }
    if (!shape[path]) {
      shape[path] = yup.object().shape(subShape);
    }
  }

  return yup.object(shape);
};

const validateForm = async (values, backendDependencies, valuesSchema, setErrors) => {
  const backendSchema = createValidationSchema(backendDependencies);
  console.log('backendSchema: ', backendSchema.describe());
  console.log('values: ', values);

  try {
    await valuesSchema.validate(values, { abortEarly: false });
    await backendSchema.validate(values, { abortEarly: false });

    return null;
  } catch (err) {
    const errors = {};
    if (err.inner) {
      err.inner.forEach((error) => {
        errors[error.path] = error.message;
      });
    }

    setErrors(errors);
    return errors;
  }
};

export default validateForm;

The code I have written is as above and you can see the following example for usage example

   validateForm(
      values,
      {
        path: 'lawControlClauses',
        data: controlClauses,
        rule: 'boolean',
        objectPathField: 'value'
      },
      legalUnitReviewNewSchema,
      formikLegalUnitReview.setErrors
    );