When using wordpress ACF, how can we programatically add new options to a choice field?

I’m importing some data, and generating posts with ACF information, which works well for text fields, and choice fields where the option already exists – but I’d like to add new options to choice fields as required.

I’d hope this is something easy to do, but starting to suspect it’s either difficult, or I’m barking up the wrong tree.

To put it another way, when looking at a choice field in the admin panel, we can type in a list of choices – I want to be able to add a choice to this list programatically

Enter each choice on a new line. For more control, you may specify
both a value and label like this: red : Red

Choices

[Input text box here]

Enter each choice on a new line. For more control, you may specify
both a value and label like this: red : Red

apache-echart how to skip null value like chart js

enter image description here

from this picture i want to remove or skip empty bar i try to change data to Null, Undifinded, ‘-‘, 0 but it not work

this is my data

var series = [
{
“name”: “Bar A”,
“type”: “bar”,
“stack”: “Bar A”,
“data”: [
1,
“-”
],
“itemStyle”: {
“color”: “#81C784”
},
“label”: {
“rotate”: 45,
“show”: true,
“position”: “inside”
}
},
{
“name”: “Bar B”,
“type”: “bar”,
“stack”: “Bar B”,
“data”: [
1,
“-”
],
“itemStyle”: {
“color”: “#81C784”
},
“label”: {
“rotate”: 45,
“show”: true,
“position”: “inside”
}
},
{
“name”: “Bar C”,
“type”: “bar”,
“stack”: “Bar C”,
“data”: [
“-“,
1
],
“itemStyle”: {
“color”: “#81C784”
},
“label”: {
“rotate”: 45,
“show”: true,
“position”: “inside”
}
},
{
“name”: “Bar D”,
“type”: “bar”,
“stack”: “Bar D”,
“data”: [
“-“,
1
],
“itemStyle”: {
“color”: “#81C784”
},
“label”: {
“rotate”: 45,
“show”: true,
“position”: “inside”
}
},
]

when using emotionjs, is it better to write all styles using it?

i’m developing a project using typeScript and have adopted emotionjs to simplify styling. however, i am wondering if the following code is efficient.

// 1. using emotionjs
import { css } from '@emotion/css';

const common = css` color: #ccc; `;

const $div = document.createElement('div');
$div.classList.add(common);

// 2. using inline-style
const $div = document.createElement('div');
$div.innerHtml = `<div style="color: #ccc;">text</div>`

as far as I understand, when styles are created using emotionjs, it modifies the CSSOM — in other words, a <style> tag is injected into the <head>, which inevitably triggers a CSSOM update.
on the other hand, setting styles using inline styles does not affect the CSSOM, but it does cause reflow and repaint.

if what I understand about the process is correct, does that mean relying solely on emotionjs for styling could lead to performance issues?

since emotionjs updates the CSSOM when applying styles, i thought excessive fragmentation(like in the code above)would result in too many injected class names, which could negatively impact runtime performance.

Why vuejs chart with data read by axios is empty?

In laravel 12 / vuejs “^3.5.13” app with “vue-chartjs”: “^5.3.2” and “chart.js”: “^4.4.8” I make chart with data read
from db :

 <template>
     <div>
         <Bar
             id="my-chart-id"
             :options="chartOptions"
             :data="chartData"
         />
     </div>
 </template>

 <script>
     import {useItemsChartStore} from "@/stores/reports/ItemsChartStore.js";

     import { Bar } from 'vue-chartjs'
     import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

     ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)


     export default {
         name: "ItemReportTable.vue",
         data() {
             return {
                 ItemsChartStore: useItemsChartStore(),
                 chartData: {
                     labels: [ 'January', 'February', 'March' ],
                     datasets: [ { data: [40, 20, 12] } ]
                     // labels: [],
                     // datasets: [ {  } ]
                 },
                 colors: [
                     '#3b82f6',
                     '#7c3aed'
                 ],

                 chartOptions: {
                     indexAxis: 'y',
                     responsive: true,
                     scales: {
                         x: {
                             ticks: {
                                 callback: value => parseFloat(value).toFixed(2) + '%'
                             },
                             beginAtZero: true,
                             max: 100
                         }
                     },
                     plugins: {
                         legend: {
                             position: 'bottom'
                         },
                         title: {
                             display: true,
                             text: 'Error!'
                         },
                         tooltip: {
                             callbacks: {
                                 label: context => { // Is not claaded
                                     console.log('callbacks context::')
                                     console.log(context)

                                     const val = context.raw
                                     return `${context.dataset.label}: ${val.toFixed(2)}%`
                                 }
                             }
                         }
                     }
                 }
             }
         },
         components: { Bar },

         computed: {
             labelDistricts() {
                 return this.ItemsChartStore.labelDistricts;
             },
             datasetsVotersCount() {
                 return this.ItemsChartStore.datasetsVotersCount;
             },
         },


         watch: {
             datasetsVotersCount(newValue) {
                 console.log('watch this.datasetsVotersCount newValue::')
                 console.log(newValue)

                 this.chartData.labels  = this.labelDistricts
                 this.chartData.datasets  = this.datasetsVotersCount

                 console.log('this.datasetsVotersCount this.chartData.labels::')
                 console.log(this.chartData.labels)

                 console.log('this.datasetsVotersCount this.chartData.datasets::')
                 console.log(this.chartData.datasets)

             }
         },

         methods: {
         },

         mounted() {
             this.ItemsChartStore.fetchItemsChart(this.$route.params.eventId);
         }
     }
 </script>

Where in mount I read data from db with axios async request and in watch datasetsVotersCount event I see that data are read.
I set valid values to chartData array and check it has valid data in vue-dev-tools. But I still default 'January', 'February', 'March' values in the chart. If I leave no data in the chartData var, then my chart is empty and
i have undefined in legend area in the bottom.

How to make it working ?

Bigint issue in JS for long Number

I don’t want to convert the number 20250130134690296n, and I also don’t want to convert it to a string. I just want to keep the plain, actual number as 20250130134690294. Is there any way to achieve this?

let a =  Bigint(20250130134690294)

console.log(a)

result =  20250130134690296n

Converting Firebase Timestamp to JS Date with correct timezone

I have some data in Firestore with a Timestamp in my local timezone (Europe/Copenhagen) and because we are in summer that is UTC+2 right now. I also have some ints in the Firestore collection to save start/end hour and minute.

I am trying to convert them to a JavaScript Date and creating a event in a Google Calendar via googleapis like this:

exports.createCalendarOnTimesCreated = functions.firestore.onDocumentCreated("times/{timeId}", async (event) => {
    google.options({ auth: serviceAccount });

    const data = event.data != null ? event.data!.data() : null;

    if (!data) {
        return;
    }

    const eventTime = data.dateAndTime as Timestamp;
    const dateStart = eventTime.toDate();
    dateStart.setHours(data.timeStartHour);
    dateStart.setMinutes(data.timeStartMinutes);
    const dateEnd = eventTime.toDate();
    dateEnd.setHours(data.timeEndHour);
    dateEnd.setMinutes(data.timeEndMinutes);

    const eventData = {
        summary: "Test",
        start: {
            dateTime: dateStart.toISOString(),
            timeZone: 'Europe/Copenhagen',
        },
        end: {
            dateTime: dateEnd.toISOString(),
            timeZone: 'Europe/Copenhagen',
        },
    };

    // Create new event
    await calendar.events.insert({
        calendarId: calendarId,
        requestBody: eventData,
    });
});

Strangly if I create a document in the collection where dateAndTime is today the date in the Google Calendar event is correct, but if I create a document where dateAndTime is tomorrow or anytime in the future the date in the Google Calendar is always one day before the date in the document in Firestore.

What am I doing wrong here?

Thank you
Søren

Electron Playwright Test Hanging due to Flask Backend

I have an Electron app that first runs its backend and awaits its connection before opening the first window like:

/**
 * Connects to the Flask app, then creates the window
 */
let flaskProc = null;
const connectToFlask = () => {
    //...
    
    //run the venv and start the script
    flaskProc = require("child_process").spawn(command, args);

    flaskProc.stdout.on('data', function (data) {  
        const output = data.toString('utf8');
        console.log("FLASK RUNNING! data:", output);
        /* Wait until Flask server is running to create the window */
        if(output.includes("Serving Flask")){
            testFlaskConnection().then((value) => {
                if(value===true){
                    //emitting an event for Playwright tests
                    createWindow();
                }
            })
            .catch(err => console.error(err));
        }
    });
    //...
}

const testFlaskConnection = () => {
    if (flaskProc) {
        console.log("Attempting connection to Flask...");
        return fetch(`${SERVER_URL}/`,{ method: "GET" })
        .then((response) =>{
            //...
            return true;
        })
        //...
    }
}

app.whenReady().then(() => {
    connectToFlask();
});

and when the window is closed, the backend shuts down like:

const shutdownFlaskConnection = () => {
    if (flaskProc) {
        return fetch(`${SERVER_URL}/shutdown`, { method:"POST" })
        .then((response) => {
            /* If the response doesn't come back (error 404), Flask has probably
            already shut down before it could be sent */
            if (!response.ok && response.status!=404) {
                console.error("Flask shutdown request failed:", response.status);
                flaskProc.kill('SIGINT');   //kill Flask jic
                flaskProc=null;
                return;
            }
            /* Otherwise, Flask was shutdown */
            console.log("Flask shutdown request successful.");
            flaskProc=null;
        })
        .catch((error) => {
            console.error("Error with shutdown request:", error);
            flaskProc.kill('SIGINT');
            flaskProc = null;
        });
    }
}

//...

let isAppQuitting=false;    //flag for on close event
let win=null;
const createWindow = () => {
    //...
    win.on('close', (evt) => {
        if(!isAppQuitting){
            evt.preventDefault();   //pause shutdown to run one last request
            console.log("Attempting graceful exit of Flask...");
            shutdownFlaskConnection().then(() => {
                //close again, properly this time
                isAppQuitting=true; //reset flag to skip if block
                win.close();    //run the event handler again
            }).catch((err) => {
                console.error(err);
                isAppQuitting=true; //reset flag to skip if block
                win.close();    //run the event handler again
            });
        }
    });
}

/**
 * When all the windows close, quit the app
 */
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin'){
        app.quit();
    }
});
/**
 * When Electron is closed through the terminal, also kill Flask
 */
app.on('quit', () => {
    if (flaskProc) {
        console.log("Quitting: Sending SIGINT to Flask process...");
        flaskProc.kill('SIGINT');
    }
});

The latter part, I suspect, is the reason this error is happening.

The app works. The problem is that I want to add some tests with Playwright and this seems to be causing problems.

Just opening and closing the app works. Both of the tests below work:

const { test, _electron: electron } = require('@playwright/test')

test('launch app', async () => {
    //NOTE: The launch path is relative to the folder the script is running from
    const electronApp = await electron.launch({ args: ['apps/frontend/src/electron/main.js'] })
    // close app
    await electronApp.close()

});
const { test, _electron: electron } = require('@playwright/test')

let electronApp = null;
test.beforeAll(async () => {
    //NOTE: The launch path is relative to the folder the script is running from
    electronApp = await electron.launch({ args: ['apps/frontend/src/electron/main.js'] });
});

test.afterAll(async () => {
    // close app
    await electronApp.close();
})


test('launch app', async () => {
    console.log("filler");
});

But the moment I try to interact with the app, the test will run until it’s timed out, even after all actions have been completed.

test('launch app', async () => {
    // Get the first window that the app opens, wait if necessary.
    const window = await electronApp.firstWindow();
    // Print the title
    console.log(await window.title());
    // close app
    await electronApp.close();
});

Opens the app, prints the title, and then closes the app, as it should, but then the test just keeps running. It then times out, fails, and I have to stop the test runner manually.
The error message I get looks like:

Running 1 test using 1 worker

  ✘  1 appslibse2e_testsmain.spec.js:15:1 › launch app (30.0s)
Index Page


  1) appslibse2e_testsmain.spec.js:15:1 › launch app ───────────────────────────────────────
    Test timeout of 30000ms exceeded.

  1 failed
    appslibse2e_testsmain.spec.js:15:1 › launch app ────────────────────────────────────────
Terminate batch job (Y/N)? y

I know that this problem is due to the Flask app because if I replace my main.js with the one from the Electron Quick Start Guide, it runs perfectly. The following message is what that prints to the terminal:

Running 1 test using 1 worker

  ✓  1 appslibse2e_testsmain.spec.js:15:1 › launch app (242ms)
Index Page

  1 passed (1.6s)

I have tried emitting a message for Playwright to pick up or a console.log() message, but neither work. It’s difficult searching for answers since this is such a specific problem.

Any help would be appreciated. Thank you for your time.

HTML input form not working correctly on some devices but works on others

The input field in my app works normally with any value, except “!” and “2” specifically.
However, when i send the link to my friends to test it it works for some but not for others. Here is the result:
1.Brave Browser — Works
2.Microsoft Edge — Doesn’t work
3.Google Chrome — Works
Here is the project: https://github.com/DanhTheAlyaSimp/Visuo
If it is a browser problem how to make sure a program works on all browsers?

What I’ve tried:
Switched to Google Chrome and it works. However it still doesn’t work on Edge, which means it’s browser dependent.

For a float number a.bc without underflow and overflow, does a.bc.toString() always ==”a.bc”? May it return something like “a.bc00000000000000000001”?

For example, I know 0.12 is not exactly equals to 12/100 in decimal because it needs to be rounded to some value. However, I’m not asking about mathematical problem , but about Javascript spec that string converting without other calculations.

My question is, if someone gives you a float number that without underflow and overflow (eg:from http response or hardcoded value):

const obj={
    "val":a.bc;
};

,does Javascript spec ensures that obj.val.toString() always return “a.bc”?

Would there be any cases that obj[“val”].a.bc.toString() return something like “a.bc00000000000000000001” (actual value of the float value that rounded)?

Is there a way to conditionally compile something in Typescript based on a compile-time expression?

With the many frameworks that that we have that allow us to build apps using web frontend technologies in many cases you might want to create an app/frontend that communicates to the backend in a different way depending on whether it’s being served as a website, or being ‘served’ by Tauri, or Electron backend, or whatever else. Is there a way I can do something like:

async function sendToBackend()
{
#ifdef IS_WEBPAGE_BUILD
     await fetch("/backend_service");
#else
     await invoke("myBackendFunctionInTauri", "args_or_whatever");
#endif
}

That will end up one or the other based on a compile-time variable or flag I can set? Typescript is purely a compile-time transpiler so it should be good at this.

Disabling checkboxes in Jquery when Any checkbox is clicked

I have the following series of checkboxes on my page:

<div class="form-group row" id="Location">
                    <div class="col">

 <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
  Any  <br />
 </label>
 <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
  Test1  <br />
 </label>
 <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
  Test2  <br />
 </label>
 <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
  Test3  <br />
 </label>
<label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
  Test4  <br />
 </label>
</div>

If the user checks “Any” box then I want the rest of the boxes to be checked and also rest of the check boxes to be disabled. This is what I have to check rest of the checkboxes if “Any” is clicked and it works.

 $("#chkLoc0").click(function () {
       $('[id^=chkLoc]:not(#chkLoc0)').prop('checked', $(this).prop('checked'));
   });

I tried to write the below code to disable rest of the check boxes if “Any” is clicked and it is not working. This is what i have:

  $("#chkLoc0").click(function () {
       $('[id^=chkLoc]:not(#chkLoc0)').prop('disabled', $(this).prop('disabled'));
   });

How can I disable all the checkboxes when “Any” check box is clicked.

Looking for a cleaner way to implement one-at-a-time expanding sections

I’ve built a working animated panel menu in React using Framer Motion. Only one section expands at a time, making the animation smooth and visually clean.

testmenu in action

However, I’d like help improving or simplifying the implementation, especially around layout, maxHeight logic, and content rendering. I feel there might be a much better way to achieve this visual effect.

I am also trying to remove the “fold” effect (best seen when expanding Section 3), and would prefer it if other sections slided off the panel rather than shrink down.

Code:

testmenu.jsx:

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import './testmenu.css';

const App = () => {
  const [expandedSection, setExpandedSection] = useState(null);

  const sections = [
    {
      key: 'section1',
      title: 'Section 1',
      content: <div>This is Section 1 content.</div>
    },
    {
      key: 'section2',
      title: 'Section 2',
      content: (
        <ul>
          <li>Item A</li>
          <li>Item B</li>
          <li>Item C</li>
        </ul>
      )
    },
    {
      key: 'section3',
      title: 'Section 3',
      content: (
        <div>
          <p>This is a third section with some text and a button:</p>
          <button style={{ marginTop: '0.5rem' }}>Click Me</button>
        </div>
      )
    }
  ];

  const expandedIndex = sections.findIndex(s => s.key === expandedSection);

  return (
    <div className="panel-wrapper">
      <motion.div layout className="menu-panel">
        <div className="panel-title">Panel Title</div>
        <hr className="divider" />
        <motion.div layout className="section-stack">
          {sections.map(({ key, title, content }, index) => {
            const isExpanded = expandedSection === key;
            const isAnyExpanded = expandedSection !== null;
            const isAbove = isAnyExpanded && index < expandedIndex;
            const isBelow = isAnyExpanded && index > expandedIndex;

            let maxHeight = '60px';
            if (isAnyExpanded) {
              if (isExpanded) maxHeight = '600px';
              else if (isAbove || isBelow) maxHeight = '0px';
            }

            return (
              <motion.div
                key={key}
                layout
                layoutId={key}
                className="section"
                animate={{ maxHeight }}
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  flexGrow: isExpanded ? 999 : 0,
                  minHeight: 0,
                  overflow: 'hidden',
                  pointerEvents: !isAnyExpanded || isExpanded ? 'auto' : 'none',
                  transformOrigin: isAbove ? 'top' : 'bottom',
                  position: 'relative'
                }}
                transition={{ duration: 0.5, ease: [0.33, 1, 0.68, 1] }}
              >
                {/* WRAPPED HEADER to prevent motion dip */}
                <motion.div layout="position">
                  <div
                    className="section-header"
                    onClick={() =>
                      setExpandedSection(isExpanded ? null : key)
                    }
                    style={{
                      height: '60px',
                      display: 'flex',
                      alignItems: 'center'
                    }}
                  >
                    {title} {isExpanded ? '▼' : '▶'}
                  </div>
                </motion.div>

                {/* Absolutely positioned content */}
                <div
                  className="section-content"
                  style={{
                    position: 'absolute',
                    top: '60px',
                    left: 0,
                    right: 0,
                    display: isExpanded ? 'block' : 'none'
                  }}
                >
                  {content}
                </div>
              </motion.div>
            );
          })}
        </motion.div>
      </motion.div>
    </div>
  );
};

export default App;

testmenu.css:

body, html, #root {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    background: #111;
    color: white;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .panel-wrapper {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 320px;
    height: 240px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .menu-panel {
    background: #1e1e2a;
    border-radius: 8px;
    padding: 1rem;
    width: 30vw;
    height: 30vh;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
  }
  
  .panel-title {
    text-align: center;
    font-weight: bold;
    cursor: pointer;
    padding: 0.5rem 0;
  }
  
  .section-header {
    font-weight: bold;
    cursor: pointer;
  }
  
  .section-content {
    font-size: 0.95rem;
    color: #ddd;
    margin: 0;
    padding: 0;
  }
  
  .section-content > *:first-child,
  .section-content p:first-child {
    margin-top: 0;
  }
  
  .section-content > *:last-child,
  .section-content p:last-child {
    margin-bottom: 0;
  }
  
  .section-stack {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    min-height: 0;
    overflow: hidden;
  }
  
  .section {
    position: relative;
  }
  
  .divider {
    border: none;
    border-top: 1px solid #444;
    margin: 0.5rem 0 0 0;
  }

I would appreciate any help towards this.

Looking for a cleaner way to implement one-at-a-time expanding sections in React + Framer Motion

I’ve built a working animated panel menu in React using Framer Motion. Only one section expands at a time, making the animation smooth and visually clean.

testmenu in action

However, I’d like help improving or simplifying the implementation, especially around layout, maxHeight logic, and content rendering. I feel there might be a much better way to achieve this visual effect.

I am also trying to remove the “fold” effect (best seen when expanding Section 3), and would prefer it if other sections slided off the panel rather than shrink down.

Code:

testmenu.jsx:

import React, { useState } from 'react';
import { motion } from 'framer-motion';
import './testmenu.css';

const App = () => {
  const [expandedSection, setExpandedSection] = useState(null);

  const sections = [
    {
      key: 'section1',
      title: 'Section 1',
      content: <div>This is Section 1 content.</div>
    },
    {
      key: 'section2',
      title: 'Section 2',
      content: (
        <ul>
          <li>Item A</li>
          <li>Item B</li>
          <li>Item C</li>
        </ul>
      )
    },
    {
      key: 'section3',
      title: 'Section 3',
      content: (
        <div>
          <p>This is a third section with some text and a button:</p>
          <button style={{ marginTop: '0.5rem' }}>Click Me</button>
        </div>
      )
    }
  ];

  const expandedIndex = sections.findIndex(s => s.key === expandedSection);

  return (
    <div className="panel-wrapper">
      <motion.div layout className="menu-panel">
        <div className="panel-title">Panel Title</div>
        <hr className="divider" />
        <motion.div layout className="section-stack">
          {sections.map(({ key, title, content }, index) => {
            const isExpanded = expandedSection === key;
            const isAnyExpanded = expandedSection !== null;
            const isAbove = isAnyExpanded && index < expandedIndex;
            const isBelow = isAnyExpanded && index > expandedIndex;

            let maxHeight = '60px';
            if (isAnyExpanded) {
              if (isExpanded) maxHeight = '600px';
              else if (isAbove || isBelow) maxHeight = '0px';
            }

            return (
              <motion.div
                key={key}
                layout
                layoutId={key}
                className="section"
                animate={{ maxHeight }}
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  flexGrow: isExpanded ? 999 : 0,
                  minHeight: 0,
                  overflow: 'hidden',
                  pointerEvents: !isAnyExpanded || isExpanded ? 'auto' : 'none',
                  transformOrigin: isAbove ? 'top' : 'bottom',
                  position: 'relative'
                }}
                transition={{ duration: 0.5, ease: [0.33, 1, 0.68, 1] }}
              >
                {/* WRAPPED HEADER to prevent motion dip */}
                <motion.div layout="position">
                  <div
                    className="section-header"
                    onClick={() =>
                      setExpandedSection(isExpanded ? null : key)
                    }
                    style={{
                      height: '60px',
                      display: 'flex',
                      alignItems: 'center'
                    }}
                  >
                    {title} {isExpanded ? '▼' : '▶'}
                  </div>
                </motion.div>

                {/* Absolutely positioned content */}
                <div
                  className="section-content"
                  style={{
                    position: 'absolute',
                    top: '60px',
                    left: 0,
                    right: 0,
                    display: isExpanded ? 'block' : 'none'
                  }}
                >
                  {content}
                </div>
              </motion.div>
            );
          })}
        </motion.div>
      </motion.div>
    </div>
  );
};

export default App;

testmenu.css:

body, html, #root {
    margin: 0;
    padding: 0;
    font-family: sans-serif;
    background: #111;
    color: white;
    height: 100vh;
    width: 100vw;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .panel-wrapper {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 320px;
    height: 240px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
  .menu-panel {
    background: #1e1e2a;
    border-radius: 8px;
    padding: 1rem;
    width: 30vw;
    height: 30vh;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    display: flex;
    flex-direction: column;
  }
  
  .panel-title {
    text-align: center;
    font-weight: bold;
    cursor: pointer;
    padding: 0.5rem 0;
  }
  
  .section-header {
    font-weight: bold;
    cursor: pointer;
  }
  
  .section-content {
    font-size: 0.95rem;
    color: #ddd;
    margin: 0;
    padding: 0;
  }
  
  .section-content > *:first-child,
  .section-content p:first-child {
    margin-top: 0;
  }
  
  .section-content > *:last-child,
  .section-content p:last-child {
    margin-bottom: 0;
  }
  
  .section-stack {
    display: flex;
    flex-direction: column;
    flex-grow: 1;
    min-height: 0;
    overflow: hidden;
  }
  
  .section {
    position: relative;
  }
  
  .divider {
    border: none;
    border-top: 1px solid #444;
    margin: 0.5rem 0 0 0;
  }

I would appreciate any help towards this.

Why is the strict equality operator slightly slower than the equality operator in javascript?

As I have read from the accepted answer here, strict equality comparison should be slightly faster than normal equality, as it doesn’t involve type coercion, quote

Strict comparison (===) will always be slightly faster, but the difference is usually negligible

However, when I tried to benchmark this in-browser, the result seems to suggest otherwise

I tried the following code, which runs both types of equality on the same two strings ("123456") for 10000 times and benchmarks their execution time.

console.time("test");for(i=0;i<10000;i++)if("123456"==="123456")continue;console.timeEnd("test");
console.time("test2");for(i=0;i<10000;i++)if("123456"=="123456")continue;console.timeEnd("test2");

I got:

test: 0.342041015625 ms
test2: 0.26318359375 ms

which suggests that normal equality should be faster than strict equality in the context of strings. Benchmarking on numbers shows similar results

console.time("test");for(i=0;i<10000;i++)if(123456===123456)continue;console.timeEnd("test");
console.time("test2");for(i=0;i<10000;i++)if(123456==123456)continue;console.timeEnd("test2");

output:

test: 0.4560546875 ms
test2: 0.316162109375 ms

why?

I am creating a React component, EmployeeValidationForm, against a detailed requirements list. I have managed to pass some but the ones stated below

These are the tests that are failing:

  • Initially, all the fields should be empty
  • Input fields functionality : should display no error for name input
    field’s if criteria is met
  • Input fields functionality : should display no error for email input
    field’s if criteria is met
  • Input fields functionality : should display no error for employee ID
    input field’s if criteria is met

Here is the code:

    import React, { useState } from "react";
    
    function EmployeeValidationForm() {
      const [name, setName] = useState("");
      const [email, setEmail] = useState("");
      const [employeeID, setEmployeeID] = useState("");
      const [joinDate, setJoinDate] = useState("");
      
      const isNameValid = /^[a-zA-Zs]{5,}$/.test(name.trim());
      const isEmailValid = /S+@S+.S+/.test(email);
      const isEmployeeIDValid = /^d{6}$/.test(employeeID);
      const isJoinDateValid = (() => {
        if (!joinDate) return false;
        const selectedDate = new Date(joinDate);
        const today = new Date();
        selectedDate.setHours(0, 0, 0, 0);
        today.setHours(0, 0, 0, 0);
        return selectedDate <= today;
      })();
    
      const isFormValid =
        isNameValid && isEmailValid && isEmployeeIDValid && isJoinDateValid;
    
      const handleSubmission = e => {
        e.preventDefault();
        setName("")
        setEmail("");
        setEmployeeID("");
        setJoinDate("");
      }
    
      return (
        <div className="layout-column align-items-center mt-20 ">
          <div className="layout-column align-items-start mb-10 w-50" data-testid="input-name">
            <input
              className="w-100"
              type="text" 
              name="name"
              value={name}
              onChange={e => setName(e.target.value)}
              placeholder="Name"
              data-testid="input-name-test"
            />
              {!isNameValid && ( 
                <p className="error mt-2">
                  Name must be at least 4 characters long and only contain letters and spaces.
                </p> 
              )}
          </div>
          <div className="layout-column align-items-start mb-10 w-50" data-testid="input-email">
            <input
              className="w-100"
              type="text"
              name="email"
              value={email}
              onChange={e => setEmail(e.target.value)}
              placeholder="Email"
            />
              {!isEmailValid && (
                <p className="error mt-2">Email must be a valid email address</p>
              )
            }
          </div>
          <div className="layout-column align-items-start mb-10 w-50" data-testid="input-employee-id">
            <input 
              className="w-100"
              type="number"
              name="employeeID"
              value={employeeID}
              onChange={e => setEmployeeID(e.target.value)}
              placeholder="Employee ID"
            />
              {!isEmployeeIDValid && (
                <p className="error mt-2">Employee ID must be exactly 6 digits</p>
              )
            }
          </div>
          <div className="layout-column align-items-start mb-10 w-50" data-testid="input-joining-date">
            <input 
              className="w-100"
              type="date"
              name="joiningDate"
              value={joinDate}
              onChange={e => setJoinDate(e.target.value)}
              placeholder="Joining Date"
            />
            {!isJoinDateValid && (
              <p className="error mt-2">Joining Date cannot be in the future</p>
            )}
          </div>
          <button 
            data-testid="submit-btn" 
            type="submit" 
            disabled={!isFormValid}
            onClick={handleSubmission}
          >
            Submit
          </button>
        </div>
      );
    }
    
    export default EmployeeValidationForm;