-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarks.js
276 lines (228 loc) · 8.21 KB
/
marks.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/** Array of courses populated from courses.json */
var courses = [];
/** Number of credits available */
var totalCredits = 240;
/** Current total percentage gained */
var totalPercentage = 40;
/** The course as stringified json from local storage */
var localCourse = localStorage.getItem('course');
/** Clone of a module row */
var $rowTemplate = $('tr.module').clone();
/** Module table's tbody */
var $tbody = $('#modules tbody');
/** Total credits input */
var $totalCredits = $('#totalCredits');
/** Course select dropdown */
var $course = $('#course');
/** Add row button */
var $addRow = $('#addRow');
/** Span of the guaranteed and predicted percentage */
var $markGuaranteed= $('#markGuaranteed');
var $markPredicted= $('#markPredicted');
/** Warning alert */
var $warning = $('#warning');
// Get courses.json which countains a courses array
$.getJSON('courses.json', function(coursesArray) {
// Set courses to the courses array we now have
courses = coursesArray;
});
// If there is a course in localstorage, load it into the table
if (localCourse) {
var data = JSON.parse(localCourse);
$course.find('option[value=' + data.id + ']').prop('selected', true);
loadFromObject(data);
}
// When .addRow is clicked, append a row to the table
$addRow.on('click', function() {
var $toAppend = $rowTemplate.clone();
$tbody.append($toAppend);
$toAppend.focus();
});
// When a .deleteRow is clicked, remove the corresponding row
$(document).on('click', '.deleteRow', function(e) {
$(this).closest('tr').remove();
updateResults();
});
// When a .markDone is clicked, toggle the done class on the row
$(document).on('click', '.markDone', function(e) {
var tr = $(this).closest('tr').toggleClass('success');
tr.find('input').prop('disabled', tr.hasClass('success'));
updateResults();
});
// When an input is changed, fire updateResults(false) with a 200ms buffer
$(document).on('keyup change', 'input', debounce(updateResults.bind(this, false), 200));
// When an input loses focus, replace X/Y with percentages
$(document).on('blur', 'input', function(e) {
var tokens = $(e.target).val().split('/');
if(tokens.length !== 2)
tokens = $(e.target).val().split(' out of ');
if(tokens.length === 2) {
$(e.target).val((Number(tokens[0]) / Number(tokens[1])) * 100);
}
});
// When course selector is changed, refresh table
$course.change(function() {
var id = $(this).val();
loadFromObject(courses[id - 1]);
});
// Allow the table to be re-ordered
$("#modules").find('tbody').sortable({
items: "tr",
cursor: 'move',
opacity: 0.6,
update: function() {
saveData();
}
});
/**
* Takes a course object and loads it into the view, adding rows for each module
* @param {Object} data The course objtect
*/
function loadFromObject(data) {
// Delete all modules
$('.module').remove();
// Set total credits
$totalCredits.val(data.credits);
// An array of jQuery objects to append
var toAppend = [];
// For each module, create a row to add to the table
$.each(data.modules, function(key, module) {
var $row = $rowTemplate.clone();
$row.find('.moduleName').val(module.name);
$row.find('.creditsWorth').val(module.credits);
$row.find('.result').val(module.mark || 40);
if(module.done)
$row.addClass('success').find('input').prop('disabled', true);
toAppend.push($row);
});
// Append rows to table
$tbody.append(toAppend);
// Update the table
updateResults(true);
}
/**
* Update the percentage of all modules
* @param {Boolean} allFields If set, all fields will be updated (not just overall percentage)
*/
function updateResults(allFields) {
totalCredits = Number($totalCredits.val());
// Get all courses, and update the percentage of each one
var updatedCourses = extractData().map(function(module) {
return $.extend(module, {
percentage: (module.credits / totalCredits) * module.result
});
});
// Update the tables with this new array
updateTable(updatedCourses, allFields);
// Persist to local storage
saveData();
}
/**
* Pull out all of the inputted data in the table
* @return {Array} An array of course objects
*/
function extractData() {
return $('tr.module').get().map(function(row) {
return {
name: $(row).find('.moduleName').val(),
credits: Number($(row).find('.creditsWorth').val()),
result: Number($(row).find('.result').val()),
percentage: Number($(row).find('.pcOfDegree').val()),
done: $(row).hasClass('success'),
el: row
};
});
}
/**
* Set all the values in the table
* @param {Array} modules Array of module objects
* @param {Boolean} allFields If set, all fields will be updated (not just overall percentage)
*/
function updateTable(modules, allFields) {
// For each module, set up the corresponding row's values
modules.forEach(function(module) {
if (allFields) {
$(module.el).find('.moduleName').val(module.name.trim());
$(module.el).find('.creditsWorth').val(module.credits);
$(module.el).find('.result').val(module.result);
}
$(module.el).find('.pcOfDegree').val(module.percentage.toFixed(2));
});
// Calculate the total mark
var mark = modules.reduce(function(accum, module) {
return accum + module.percentage;
}, 0);
var markGuaranteed = modules.reduce(function(accum, module) {
return module.done ? accum + module.percentage : accum;
}, 0);
// Confetti time!
totalPercentage = mark;
if (window.changeConfetti) {
changeConfetti();
}
// Set guaranteed and predicted value and progress bar width
$markGuaranteed.text(markGuaranteed.toFixed(2)).parent().width(markGuaranteed + '%');
$markPredicted.text(mark.toFixed(2)).parent().width((mark - markGuaranteed) + '%');
// Calculate the total number of credits inputted
var totalCreditsSupplied = modules.reduce(function(accum, module) {
return accum + module.credits;
}, 0);
if (totalCredits === totalCreditsSupplied) {
// All good, hide warning
$warning.hide();
} else if(totalCredits > totalCreditsSupplied) {
// Too few credits
$warning.text('Not enough credits; add more modules').show();
} else if(totalCredits < totalCreditsSupplied) {
// Too many credits
$warning.text('Too many credits supplied').show();
}
}
/**
* Persists the inputted course data to local storage
*/
function saveData() {
// Get currently selected course
var $selectedCourse = $course.find('option:selected');
// Build course object
var course = {
id: $selectedCourse.val(),
name: $selectedCourse.text(),
credits: totalCredits,
modules: [],
};
// Add modules to course object
$tbody.find('.module').each(function(index, module) {
module = $(module);
course.modules.push({
name: module.find('.moduleName').val(),
credits: module.find('.creditsWorth').val(),
mark: module.find('.result').val(),
done: module.hasClass('success')
});
});
// Save course object
localStorage.setItem('course', JSON.stringify(course));
}
/**
* Debounce a function, from Underscore.
* @param {function} func The function to be called
* @param {int} wait The function will be called after it stops being called for N milliseconds
* @param {bool} immediate If `immediate` is passed, trigger the function on the leading edge, instead of the trailing.
* @return {function} a function, that, as long as it continues to be invoked, will not be triggered
*/
function debounce(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
}