I am a newbie in javascript.
I work three shifts and want to control events in home assistant via node-red.
I wrote a short script using various examples, it only works until the end of the table.
I can’t get it to loop, so here I am asking for help.
I want to go back to the beginning of the array after day 20 in the change cycle.
var dayStart = new Date(2023, 2, 4);
const list = ['night1', 'night2', 'night3', 'night4',
'free_n', 'afternoon1', 'afternoon2', 'afternoon3', 'afternoon4',
'free_a', 'morning1', 'morning2', 'morning3', 'morning4',
'free1', 'free2', 'free3', 'free4', 'free5', 'free6'];
const date = new Date;
var day = Math.floor((date.getTime() - dayStart.getTime()) / (1000 * 60 * 60 * 24));
var day = (day + 1);
var change = (list[(day - 1)]);
msg.day = day;
msg.payload = change;
return msg;
2
Answers
you can add a new variable which resets to 0 every time it went over day 20. For example, let’s name the new variable dayArray
outside the loop, add
var dayArray = 0
and inside the loop you can add dayArray by 1, just like you did to the day variable you have right now, then add an if statement. If dayArray is bigger/equal than 20, then dayArray = 0
so this is what your code will be:
Please let me know if this works or not, I am not sure of what you’re trying to do with the code, so I answered based of what you asked for in the description
Edit: After some thinking, why not just put % 20 after the (day – 1). % means remainder after division. so 21/20 is 1 with 1 remainder. so 21 % 20 will return 1. So you can simply just add % 20 after (day – 1)
If I understand correctly, when 20 * k + n days have passed since
dayStart
, you need the nth element of the array.To achieve this, you can use the remainder of the division day / 20. In all programming languages I know, there is what we call the remainder operator. You can find more details here. In JavaScript, you would want to write
Also, I would consider day
day + 1
andday - 1
unnecessary because arrays in JavaScript are 0-based and the result saved inday
is also 0-based. So, the final code should look like this (including some more improvements to make it clean):