I'm working on a simple registration system which displays the number of seats available in a particular workshop. It's built in Google Apps Script which runs with a JavaScript syntax.
I build an array of Class objects for the user when they log in. One of the object keys is seats, which shows the available number of spots left in the workshop. To get that, I compare the master list of classes to get the max number of registrants to the current registration list.
Class Object
[{
date: 4/10/2017,
title: "Workshop 1",
desc: "A string description for 1",
seats: ""
}]
Google Sheets table
| date | title | description | seats | |
|-----------|------------|----------------------------|-------|---|
| 4/10/2017 | Workshop 1 | A string description for 1 | 20 | |
| 5/10/2017 | Workshop 2 | A string description for 2 | 25 | |
Current Registrations
| user | class0 | class1 |
|-------|-----------|-----------|
| user1 | 4/10/2017 | |
| user2 | 4/10/2017 | 5/10/2017 |
| | | |
Script
// Set the count variable
var count;
// Sessions the user is not registered for
for(var i=0; i<sessions.length; i++) {
// Look the class up in the master list
for(var j=0; j<allSessionsData.length; j++) {
// Find the stored date in the master list
var date = allSessionsData[j][0];
// match the session dates to find the max seats
if(sessions[i].date === date) {
sessions[i].seats = allSessionsData[j][5];
}
}
}
// Reopen the sessions loop to get the current counts
for(var i=0; i<sessions.length; i++) {
var count = sessions[i].seats;
// Get the current 2D registrations array
for(var j=0; j<allRegsData.length; j++) {
for(var k=0; k<allRegsData[j].length; k++) {
if(sessions[i].date === allRegsData[j][k]) {
count--;
sessions[i].seats = count;
}
}
}
}
// Return the updated array
return sessions;
}
The function would return 18 for the 4/10 date and 24 for the 5/10. The script is working but I'm wondering if this should be condensed into one loop and why. I know "best practice" is subjective, but it feels redundant to build one array only to reopen it immediately within the same function.
sessions[i].seats = count;out of the double-loop and place it before the end of the main loop. Or you could do without the count and use--sessions[i].seats;