Skip to content
Advertisement

How to update React properties after a delay in time and constantly sort an array to the nearest specific number X?

I’m working on a elevator simulator in React JS with typescript. It’s quite simple, there are 6 buttons on every floor for the 6 floors to go to the chosen floor. And when you click on one of the buttons the color changes so you know it’s activated. The elevator also got a Up and Down button to go 1+ or 1- but I already done that.

Here is the code for the floors. App.tsx

JavaScript

Here is the code for the floor buttons. NumberBtns.tsx

JavaScript

Questions:

So I have 2 questions.

1: How to make it when I click on multiple buttons at the same time the delay when switching floors is still the same.

2: How to make it that it always goes to the nearest floor For example, when the elevator is on the fifth floor and you press the buttons 0, 1, and 3 in this order, the elevator must recognize that the most efficient order to stop is 3 -> 1 -> 0.

Advertisement

Answer

Calculate the distance from the starting floor to all the floors clicked and sort the array from closest to farthest.

JavaScript

Just to elaborate, it calculates the distance of two numbers from 1, i.e. for

  • a=-10 and b=4, the distances are 11 and 3 respectively. The function returns a positive number, so 4 comes before -10 in the sorted array.

  • For a=-1 and b=4, the distances would be 2 and 3, the function returns a negative number so -1 comes before 4 in the array.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement