Anonymous user
Fractran: Difference between revisions
→{{header|JavaScript}}: Removed unused variables, made the functions not rely on global variables nor have collateral effects, the compile function stores the result of the regex parse for each iteration, so it's not re-computed 3 times
(→{{header|JavaScript}}: Removed unused variables, made the functions not rely on global variables nor have collateral effects, the compile function stores the result of the regex parse for each iteration, so it's not re-computed 3 times) |
|||
Line 1,888:
=={{header|JavaScript}}==
<lang javascript>
// Parses the input string for the numerators and denominators
function compile(prog, numArr, denArr) {▼
let result;
▲function compile(prog){
numArr.push(result[1]);
▲ var regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
denArr.push(result[2]);
}▼
return [numArr, denArr];
▲ prog = regex.exec(prog)[3];
▲ }
}
// Outputs the result of the compile stage
function dump(
let output = "";
document.body.innerHTML += num[i]+"/"+den[i]+" ";▼
for (let i in numArr) {
output += `${numArr[i]}/${denArr[i]} `;
}▼
return `${output}<br>`;
}
// Step
function step(val, numArr, denArr) {
var i=0;▼
while (i < denArr.length && val % denArr[i] != 0) i++;
return
}
// Executes Fractran
function exec(val, i, limit, numArr, denArr) {
let output = "";
while (val && i < limit) {
val = step(val, numArr, denArr);
▲ }
return output;
}
// Main
// Outputs to DOM (clears and writes at the body tag)
compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1");▼
let body = document.body;
▲let [num, den] = compile("17/91 78/85 19/51 23/38 29/33 77/29 95/23 77/19 1/17 11/13 13/11 15/14 15/2 55/1", [], []);
body.innerHTML += exec(2, 0, 15, num, den);
</lang>
|