-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
74 lines (57 loc) · 2.05 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
document.getElementById('fileInput').addEventListener('change', function() {
const files = getJackfiles(this.files);
if (files.length === 0) {
alert("Sorry, ya gotta have .jack files.");
return;
}
const directoryName = getDirectoryName(this.files);
const codeFromFiles = [];
for (let i = 0; i < files.length; i++) {
const reader = new FileReader();
reader.onload = () => {
codeFromFiles.push(reader.result);
if (i === files.length - 1) {
const fileNames = files.map(file => file.name.substring(0, file.name.indexOf('.')));
codeFromFiles.forEach((file, index) => download(fileNames[index] + '.json', compileFile(file)));
}
}
reader.readAsText(files[i]);
}
});
document.getElementById('inputCode').addEventListener('click', function() {
const codeInput = document.getElementById('codeInput').value;
console.log(codeInput);
if (codeInput !== '') download('program.hack', compileFile(codeInput));
});
//////////////////////////////////////
function getDirectoryName(uploadedContent) {
const relativePath = uploadedContent[0].webkitRelativePath;
return relativePath.substring(0, relativePath.indexOf('/'));
}
function getJackfiles(files) {
const result = [];
for (let i = 0; i < files.length; i++)
if (getFileExtension(files[i].name) === '.jack')
result.push(files[i]);
return result;
}
function getFileExtension(fileName) {
return fileName.substring(fileName.indexOf('.'));
}
//////////////////////////////////////
function download(filename, text) {
const element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
//////////////////////////////////////
function compileFile(fileText) {
return analyzeSyntax(fileText);
}
function analyzeSyntax(fileText) {
return JSON.stringify(parse(tokenize(stripWhitespace(fileText))), null, 2);
}