-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreadInventory.js
85 lines (58 loc) · 1.7 KB
/
readInventory.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
var itemArray = [];
function readInventoryFile() {
var fileContents;
// Get inventory file contents using XMLHttpRequest
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "../inventory.txt", false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState == 4) {
if (rawFile.status == 200 || rawFile.status == 0) {
fileContents = rawFile.responseText;
}
}
};
rawFile.send(null);
// Split into lines
var fileLines = fileContents.split("\n");
// Remove comment lines and empty lines
while (true) {
var doContinue = false;
for (var i = 0; i < fileLines.length; i++) {
// Remove lines that start with "//" (comments)
if (fileLines[i].charAt(0) == "/" && fileLines[i].charAt(1) == "/") {
fileLines.splice(i, 1);
doContinue = true;
break;
}
// Remove lines that are empty
if (fileLines[i] < " ") {
fileLines.splice(i, 1);
doContinue = true;
break;
}
}
// Restart check if invalid line has been found and removed
if (doContinue == true) {
continue;
} else {
break;
}
}
// Store elements into itemArray
for (var i = 0; i < fileLines.length; i++) {
itemArray[i] = fileLines[i].split(",");
}
// Store array in session storage
sessionStorage.setItem("inventory", JSON.stringify(itemArray));
}
function checkInventoryLoaded() {
// Check if inventory array is currently stored in session storage
var data = sessionStorage.getItem("inventory");
var itemArray = JSON.parse(sessionStorage.getItem("inventory"));
if (data == null) {
// Set inventory if inventory has not already been set
readInventoryFile();
} else {
console.log("The inventory array is already populated. It won't get populated again.");
}
}