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
var num = new Array();
function compile(prog, numArr, denArr) {
var den = new Array();
var let regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
var val ;
let result;
 
progwhile (result = regex.exec(prog)[3];) {
function compile(prog){
numArr.push(result[1]);
var regex = /\s*(\d*)\s*\/\s*(\d*)\s*(.*)/m;
denArr.push(result[2]);
while(regex.test(prog)){
num.push(regex.exec( prog) = result[13]);
}
den.push(regex.exec(prog)[2]);
return [numArr, denArr];
prog = regex.exec(prog)[3];
}
}
 
// Outputs the result of the compile stage
function dump(prognumArr, denArr) {
for(var i=0; i<num.length; i++)
let output = "";
document.body.innerHTML += num[i]+"/"+den[i]+" ";
for (let i in numArr) {
document.body.innerHTML += "<br>";
output += `${numArr[i]}/${denArr[i]} `;
}
return `${output}<br>`;
}
 
// Step
function step(val, numArr, denArr) {
var i=0;
while(i<den.length && val%den[let i] != 0) i++;
while (i < denArr.length && val % denArr[i] != 0) i++;
return numnumArr[i] * val /den denArr[i];
}
 
// Executes Fractran
function exec(val, i, limit, numArr, denArr) {
var i = 0;
let output = "";
while (val && i < limit) {
document.body.innerHTML += i+": "+val+"<br>";
val output += step(`${i}: ${val)}<br>`;
val = step(val, numArr, denArr);
i ++;
var i=0++;
}
i ++;}
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;
dump();
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", [], []);
var limit = 15;
document.body.innerHTML += dump(num[i]+"/"+, den[i]+" ");
exec(2);
body.innerHTML += exec(2, 0, 15, num, den);
</lang>