Decreasing the complexity of the JS algorithm for creating slots based on days of the week

Trying to generate slots in future based on availableTimes, slots are nothing but they have start time and end time based on slotSize and startTime

Example data:

availableTimes: 
{
  TUESDAY: [{ dayOfTheWeek: "TUESDAY", start: 8, end: 10 }],
},
daysInFuture: 1,
timeZone: "Australia/Melbourne",
slotSizeInMinutes: 60,
timeStamp: 1640041590364

Based on this availableTime Data and considering current date is

2021-12-21T08:00:00.000+11:00

it should return

[
    {
      ref: "2021-12-21T08:00:00.000+11:00",
      startTime: "2021-12-21T08:00:00.000+11:00",
      endTime: "2021-12-21T09:00:00.000+11:00",
      available: true,
    },
    {
      ref: "2021-12-21T09:00:00.000+11:00",
      startTime: "2021-12-21T09:00:00.000+11:00",
      endTime: "2021-12-21T10:00:00.000+11:00",
      available: true,
    },
  ]

which is working as expected, I just want to decrease the complexity of the function.

function generateTimeSlots(
  availableTimes: {
    [x: string]: MenuAvailability[];
  },
  daysInFuture: number,
  timeZone: string,
  slotSizeInMinutes: number,
  timeStamp: number
): orders.TimeSlot[] {
  const timeSlots = [];

  for (let j = 0; j <= daysInFuture; j++) {
    let currentDate = DateTime.fromMillis(timeStamp)
      .setZone(timeZone)
      .plus({ days: j });

    const currentDay = currentDate.weekdayLong.toUpperCase() as DayOfTheWeek;
    const slotsForTheDay = availableTimes[currentDay] ?? [];

    for (let i = 0; i < slotsForTheDay.length; i++) {
      const startHour = slotsForTheDay[i].start;
      const endHour = slotsForTheDay[i].end;

      const numOfSlots = ((endHour - startHour) * 60) / slotSizeInMinutes;

      const addMinutes = (date: DateTime, minutes: number) => {
        return DateTime.fromISO(date.toISO()).plus({ minutes: minutes });
      };

      currentDate = currentDate.set({
        hour: startHour,
        minute: 0,
        second: 0,
        millisecond: 0,
      });

      for (let i = 0; i < numOfSlots; i++) {
        timeSlots.push({
          ref: currentDate.toISO(),
          startTime: currentDate.toISO(),
          endTime: addMinutes(currentDate, slotSizeInMinutes).toISO(),
          available: true,
        });
        currentDate = addMinutes(currentDate, slotSizeInMinutes);
      }
    }
  }

  return timeSlots;
}

Gradually opening sections addEventListener input

I have an accordion. The first section is open by default, the others are closed, after I fill the first one opens the next, the filled section is closed. I use addEventListener (" input "() => to dynamically read the results. The problem is that when I fill the second section and want to go to section 3, section 2 is closed and then opened.

The problem is listening to addEventListener (" input "() => since it listens to all changes. But the fact is that after the second section is closed, the values in it do not change in any way.

How to solve this problem? I need to consistently open the sections, the filled ones are closed.

window.document.addEventListener("input", () => {
  //check values
  let agesValues =
    age &&
    age.value !== age.value.defaultValue &&
    age.value !== null &&
    age.value !== "";

  if (
    (agesValues === true && male.checked) ||
    (agesValues === true && female.checked)
  ) {
    let inpush = () => {
     
      //show first section result
      blockresult1.classList.add("visible");
      //show second section inputs
      sectondSection.classList.remove("collapse");
    };
    setTimeout(inpush, 2000);
  }
  if () {
  
    if () {
    
      //show secons section result
      blockresult2.classList.add("visible");
      //close the section when it is full
        sectondSection.classList.add("collapse");
     
    }
  }
  if (
 my check
  ) {
  
    ) {
      let inpush = () => {
        
        changeButton3.classList.add("visible");
    
        thirdSection.classList.add("collapse");
      
        blockresult3.classList.add("visible");

      my actions
      
  
      };
      setTimeout(inpush, 2000);
    }
  }
.visible {
  display: block;
}
.collapse {
  display: none;
}
<form class="stepTwo-profile" id="formStepTwo">
    <p class="stepTwo-profile-title">Демография</p>
    <div class="stepTwo-profile-item">
      <a href="#" class="stepTwo-profile-item-change1">Изменить</a>
      <div class="stepTwo-profile-result1">
        <p class="stepTwo-profile-result1-text">
          Возраст пациента:<span
            class="stepTwo-profile-result1-text-sub"
            id="resultAge"
          ></span>
        </p>
        <p class="stepTwo-profile-result1-text">
          Пол:<span
            class="stepTwo-profile-result1-text-sub"
            id="resultGender"
          ></span>
        </p>
      </div>
      <div id="firstsection">
        <label for="age"
          >Возраст пациента<input
            type="number"
            class="stepTwo-profile-item-textAge"
            name="age"
            min="0"
            max="80"
            maxlength="2"
            id="age"
        /></label>
        <p class="stepTwo-profile-item-smTitle">Пол</p>
        <label for="male">
          <input type="radio" name="gender" id="male" value="male" />Мужской
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>

        <label for="female">
          <input type="radio" name="gender" id="female" value="female" />Женский
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
      </div>
    </div>
    <p class="stepTwo-profile-title">Статус пациента и заболевания</p>
    <div class="stepTwo-profile-item">
      <a href="#" class="stepTwo-profile-item-change2">Изменить</a>
      <div class="stepTwo-profile-result2">
        <p class="stepTwo-profile-result2-text">
          Предшествующая терапия:<span
            class="stepTwo-profile-result1-text-sub"
            id="trueTerapy"
          ></span>
        </p>
        <p class="stepTwo-profile-result2-text">
          Общее состояние и коморбидность:<span
            class="stepTwo-profile-result1-text-sub"
            id="OverStatus"
          ></span>
        </p>
      </div>
      <div id="sectondSection">
        <p class="stepTwo-profile-item-smTitle">Предшествующая терапия</p>

        <label for="prev-terapy1">
          <input type="radio" name="prev-terapy" id="prev-terapy1" />Нет spa
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
        <label for="prev-terapy2">
          <input type="radio" name="prev-terapy" id="prev-terapy2" />Радикальное
          лечение завершено <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
        <label for="prev-terapy3">
          <input type="radio" name="prev-terapy" id="prev-terapy3" />Одна линия
          терапии <span class="stepTwo-profile-item-radionbtn"> </span
        ></label>
        <label for="prev-terapy4">
          <input type="radio" name="prev-terapy" id="prev-terapy4" />Две или
          более линии терапии
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>

        <p class="stepTwo-profile-item-smTitle smTitleSecondsChilds">
          Общее состояние и коморбидность
        </p>
        <label for="status1">
          <input type="radio" name="status" id="status1" />ECOG 0-1
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>
        <label for="status2">
          <input type="radio" name="status" id="status2" />ECOG 2
          <span class="stepTwo-profile-item-radionbtn"></span
        ></label>
        <label for="status3">
          <input type="radio" name="status" id="status3" />ECOG 3-4 | высокая
          коморбидность
          <span class="stepTwo-profile-item-radionbtn"></span>
        </label>
      </div>
    </div>
    </form>

It should be like this
It should be like this

What do I get after a couple of seconds

What do I get after a couple of seconds

enter image description here

node js express use app.get with created name to redirect to it

I have code below. We post room name with ajax to url /room-api

function getCreatedRoomName(x){

  $.ajax({
    type: "POST",
    url: "/room-api",
    data: { roomname: x },
    success: function(data) {
    },
    error: function(jqXHR, textStatus, err) {
    alert('text status '+textStatus+', err '+err)
    }
    });

  return x;
}

app.js

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


var room_name;

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;
  console.log(room_name);
});

Then we receive that data with app.post as you can see above. How can I create a new app.get with created name? I tried this.

app.post('/room-api', isLoggedIn, function(req, res){
  room_name = req.body.roomname;

  app.get(`/${room_name}`, isLoggedIn, function(req, res){
      res.redirect(`/${room_name}`);
  });

  console.log(room_name);
});

But it doesn’t work.

Open default new-tab page of Chrome by javascript

I am building an extension for chrome, it customizes new tab of chrome. In that page, there is an option to open default new-tab page of chrome. I tried a solution by chrome-internal :

chrome.tabs.update({
        url:'chrome-internal://newtab/'
    });

But it is not supported anymore. Are there any solution for this.
Thank you so much! Sorry for my English

Changing color of an id with Javascript

I get all movie datas from Firebase and also i get score of the movies. If the score of the movie is higher than 70, then i will change color of the id as “deepskyblue”, if it is 50 or higher it will be “orange” and lastly if it is lower than 50 it will be “crimson”(red). When i do this, it only changes my first movie’s id’s color. But i wanna change all of them. How can i do this?

My Website

My Website

Console.log(i)

console

  var movieNo = 0;
let html = '';
var body = document.getElementById('editor');
var body2 = document.getElementById('week');

function AddItemsToTable(name, score, img, id) {
  var movies = `<div class="content"><img src="${img}" ><p><a href="Admin.html?movieId=${id}">${name}</a></p> <p> <i class="fa fa-star" id="star"></i>&nbsp;<a class="scoretxt">${score}</a> </p> </div>`;
  html = movies;

  body.innerHTML += html;
  body2.innerHTML+=html;

}


        function AddAllItemsToTable(TheMovies){
            movieNo=0;
            var counter=0;

            TheMovies.forEach(element => {
              if (counter===6) {
                return;
              }
                AddItemsToTable(element.movieName, element.movieScore, element.movieImage, element.movieId);
                var i = document.getElementsByClassName("fa fa-star")[element.movieId];
                console.log(i);
                if (element.movieScore>=70) {
                  i.style.color= "deepskyblue";//good movie

                }
                  else if (element.movieScore>=50) {
                    i.style.color= "orange";//not bad
                  }
                  else {
                    i.style.color="crimson";//bad movie
                  }

                counter++;

        });

      }

        function getAllDataOnce(){
            const dbRef=ref(db);
            get(child(dbRef,"Movies"))
                    .then((snapshot)=>{
                        var movies=[];
                snapshot.forEach(childSnapshot => {
                    movies.push(childSnapshot.val())
                });
                AddAllItemsToTable(movies);
            });
        }
            window.onload= getAllDataOnce;
          <div class="body" id="body">

              <div class="baslik">Opening This Week</div>
              <div class="baslik2"><a href="series.html">See all</a></div>
              <div id="week">

              </div>
                <div class="baslik">Editor's Picks</div>
                <div class="baslik2"><a href="movies.html">See all</a></div>
<div id="editor">

</div>


</div>

How to modify the initial canvas each time use Caman.js , instead of the last result?

I am trying to write a web page which can do some edit to a photo ,like brightness . And I choose a library called Caman.js to achieve my goal .But when I edit the brightness of the photo with this.brightness(…).render() ,I find that the picture could not return to its original state,it will become pure white or black , It seems that the picture has lost a lot of information .

And I find a tutorial on youtube ,and it have the same problem (https://codepen.io/bradtraversy/pen/qoJZBy ). But the example on the official website( http://camanjs.com/examples/ ) is good ,want to know how to do that .

<input type="range" min="0" max="20" value="10" id="slider_bright"/>

<script>
Caman("canvas",image_src,() => {
    this.render();
  })

const slider_bright = document.getElementById('slider_bright')
var pre_slider_bright_value = 20;

slider_bright.addEventListener('input',()=>{
    Caman("canvas",image_src,function () {
        if(pre_slider_bright_value<slider_bright.value*1){
            //decrease brightness 
            this.brightness(slider_bright.value*1 - pre_slider_bright_value).render();
        }else{
            //increase brightness
            this.brightness(slider_bright.value*1 - pre_slider_bright_value).render();
        }
        pre_slider_bright_value = slider_bright.value    
      })
})
</script>

render nested object after combining in react?

i want to render below JSON to the image shown

enter image description here

let finalSplit = [
    {
      start: "73",
      end: "76",
      splits: [
        {
          word: "Now",
          start: "73",
          color:"#FF6262",
          name:"extra",
          end: "76",
        },
      ],
    },
    {
      start: "27",
      end: "72",
      splits: [
        {
          word: "GitHub Actions",
          start: "31",
          name:"sub1",
          color:"#DFF652",
          end: "45",
        },
        {
          word: "the GitHub Actions “New Workflow” experience.",
          start: "27",
          name:"main",
          color:"#62FF8E",
          end: "72",
        },
        {
          word: "GitHub",
          start: "31",
          name:"sub2",
          color:"#9483FF",
          end: "37",
        },
      ],
    },
  ];
  

i tried to loop each array and render but since it format it have duplicate not able to render aggregated version

const Mark = () => {
    
    return (
        <>
        {
            finalSplit.map((i)=>{
                return (
                    <div>
                        i.split.map((j)=>{
                            <div>{j.text}</div>
                        })
                    </div>
                )
            })
        }
        <>
    );
}

need to some how generate other structure
text : “announcing improvements to the GitHub Actions “New Workflow” experience. Now, when you want to create”
and each place we get offsets also

Looking to apply for my first developer position [closed]

I am just starting my journey as a Front-End Developer. I taught myself Html/CSS and JavaScript, will that be enough to apply for my first position?
I am currently working on projects and my portfolio, my roadmap for myself is Html, CSS, JavaScript, React, Typescript, nodejs, python, graphQl, and AWS. I haven’t thought of what database I want to work with yet. But I am looking for someone to just talk too about what’s next.

Add to cart button does not work on mobile – Woocommerce

I am developing a Woocommerce website using wordpress and Neve wordpress theme. I am also using plugin wp-configurator. On desktops, everything is working fine I can add product to the cart and everything is working correctly. But on mobile, afer I choose configuration and tap on the button “Add to cart”, I just see the hover of the button but nothing happens.
What I already tried:

  • switch to another theme
  • reset permalinks
  • disable all plugins (I kept just woocoommerce and wp-configurator, after I disabled also wp-configurator, the button started to work)

Any suggestions, please?

How to toggle styles by using click function anywhere on the screen

I’m trying change styles of element by clicking anywhere on the screen, but it’s not working. can anyone help me out. thankyou.

   <style>
    #myDIV {
      width: 100%;
      padding: 50px 0;
      text-align: center;
      background-color: lightblue;
      margin-top: 20px;
    }
    </style>
 
   <p>Click to toggle</p>
   <div id="myDIV">This is my DIV element.</div>
    
    <script>
    window.addEventListener('click', 
    function myFunction() {
      var x = document.getElementById("myDIV");
      if (x.style.width === "100%") {
        x.style.width = "10%";
      } else {
        x.style.width = "100%";
      }
    }
    </script>

How do I resolve the “Module not found: Can’t resolve [css file] in [directory]” when deploying next.js site to Netlify?

I am trying to deploy this site to netlify: https://github.com/Koda-Pig/joshkoter.com
But I am getting this error:

10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages'
10:02:31 AM: > Build failed because of webpack errors

My next.config.json file looks like this:

module.exports = {
   reactStrictMode: true
 }
 
 const withVideos = require('next-videos')
 
 module.exports = withVideos()

According to Next.js website, there is built-in support for CSS modules, and Netlify doesn’t seem to have a problem with any of the other CSS modules I’ve created, so I don’t understand why there is a a webpack error.

I have tried specifying a CSS loader in next.config.js like this:

module.exports = {
   reactStrictMode: true,
   module: {
    rules: [
      {
        test: /.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/
      },
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      }
    ]
  }
 }
 
 const withVideos = require('next-videos')
 
 module.exports = withVideos()

I also tried with this config:

module.exports = {
   reactStrictMode: true,
   module: {
    rules: [
      {
        test: /.css$/i,
        use: ["style-loader", "css-loader"],
      },
    ],
  },
 }
 
 const withVideos = require('next-videos')
 
 module.exports = withVideos()

But I got the same error message. This is my first time deploying a next.js site to Netlify, so forgive me if I am missing something obvious.

Any help would be greatly appreciated.

How to insert elements into specific index in a 2D array in javascript?

I have an object that looks like below

const tableData = [
    {
        
        "Location": "London",
        "Status": "Unknown"
    },
    {
        
        "Location": "Delhi",
        "Status": "Reachable"
    },
    {
        
        "Location": "Berlin",
        "Status": "Unknown"
    },
    {
        
        "Location": "Tokyo",
        "Status": "Busy"
    },
]

Now I want to create a 2D array which will hold this information in a certain way. Here is my code below

const statusOrder = {"Reachable": 0, "Busy": 1, "Unknown": 2}
let statusOrderInfo = Array(Object.keys(statusOrder).length).fill([]);
for(let i=0; i< tableData.length; i++) {
    const status = tableData[i]["Status"].trim()
    const statusIndex = statusOrder[status]
    statusOrderInfo[statusIndex].push(tableData[i])
}
console.log(statusOrderInfo)

As you can see I want each item of the tableData object to be in a certain index of the 2D array. So the item that contains Status as Reachable should be at index 0, the item that contains the Status as Busy should be at index 1 and so on.

So the final output should look like

[
   [
      {
         "Location":"Delhi",
         "Status":"Reachable"
      }
   ],
   [
      {
         "Location":"Tokyo",
         "Status":"Busy"
      }
   ],
   [
      {
         "Location":"London",
         "Status":"Unknown"
      },
      {
         "Location":"Berlin",
         "Status":"Unknown"
      }
   ]
]

But I get a wrong output on running the above code even though I am targeting the correct index. What’s wrong in my approach?

DiscordJS v13 – Make the user confirm before executing something or store data so it would execute after user confirmed

I have a clear command that is implemented like this

async execute(interaction) {
  const amount = interaction.options.getInteger('amount')
  
  if (interaction.member.permissions.has(Permissions.FLAGS.ADMINISTRATOR)) {
    if (amount <= 100) {
      interaction.channel.bulkDelete(amount)
      .then(console.log(`Cleared ${amount} messages`))
      .catch(console.error)
      await interaction.reply({ content: `Cleared `${amount}` messages`, ephemeral: true })
    } else {
      interaction.channel.bulkDelete(100)
      await interaction.reply({ content: `Cleared `100` messagesnIt seems like you've somehow bypassed the 1-100 integer limitn>100 clear is dangerous and won't be implemented (learning from past mistake)`, ephemeral: true })
    }
  } else {
    await interaction.reply({ content: `You can't use the `clear` command. It is restricted to admins-only for now.`, ephemeral: false })
  }
}

Before I’ve tried to reply with an ephemeral response showing buttons labeled Yes/No asking if they really want to clear messages but I don’t know how to store the numbers so after pushing the button it would fail (and I lost the code since I didn’t commit that piece of code)

How can I make it so it could store the clear amount somewhere somehow that can’t be overwritten accidentally when someone else use the clear command somewhere else so after pushing the button then it will actually clear (since the function that handles button presses and the function that handles commands execution are 2 different funcs)

Any better idea than this is appreciated (btw im not a native English speaker so it might sounds weird here and there)

Add Drag and Drop in ul, li multilevel costume tree view using JQuery without any Plugin

I have created custom tree view using ui and li.
I want to add drag and drop on top of it without any custom plugin. Any child can be dragged in inside any li node.

like in this image 3rd parties can drag into Asset Management as child.
enter image description here

I have used $("$id").sortable(); but it’s just working in single child level only, i want to add it on multilevel.

example : http://wwwendt.de/tech/fancytree/demo/sample-ext-dnd.html