-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
85 lines (64 loc) · 2.09 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const BASE_SITE = "http://localhost:8888";
const ROOM_NUMBER_REGEX = /([a-z]+)(\d+)/i;
const shuffle = array => {
const shuffledArray = array.slice()
for (let i = shuffledArray.length - 1; i > 0; i--) {
const rand = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[rand]] = [shuffledArray[rand], shuffledArray[i]];
}
return shuffledArray;
}
const createRoomElement = roomSpec => {
const roomId = roomSpec.ID;
const numberOfSeats = roomSpec.number_of_seats;
const match = ROOM_NUMBER_REGEX.exec(roomId);
if (match === null) {
throw new Error("Invalid Room Id!");
}
const roomNumber = match[2];
const $roomDiv = $("<div>");
$roomDiv.append(`<h2> ${roomNumber} </h2>`);
$roomDiv.append(`ID: ${roomId}<br>`);
$roomDiv.append(`number of seats: ${numberOfSeats}<br>`);
$("#classrooms").append($roomDiv);
};
const studentListElement = (students) => {
const $studentList = $("<ul>");
students.forEach(student => {
$studentList.append(`<li> ${student} </li>`)
});
return $studentList;
};
const createCourseElement = courseSpec => {
const {subject, trimester, students} = courseSpec;
const $courseDiv = $("<div>");
$courseDiv.append(`<h2> ${subject} </h2>`);
$courseDiv.append(`<h3> ${trimester} </h3>`);
$courseDiv.append(`<ol>`);
$courseDiv.append(studentListElement(shuffle(students)));
$courseDiv.append(`</ol>`);
$("#courses").append($courseDiv);
};
const fetchRoomData = (roomFilename) => {
const url = `${BASE_SITE}/${roomFilename}`;
return window
.fetch(url)
.then(response => response.json())
.catch(error =>
alert(`There was an error reading from the file: ${roomFilename}`)
);
};
const displayClassroomInfo = () => {
return fetchRoomData("./data/rooms.json").then(roomList => {
roomList.forEach(createRoomElement);
});
};
const displayCoursesInfo = () => {
return fetchRoomData("./data/courses.json").then(courseList => {
courseList.forEach(createCourseElement);
});
};
const displayAllTheInfo = () => {
displayClassroomInfo().then(displayCoursesInfo);
};
$(displayAllTheInfo);