I'm losing my mind with this Problem. I wrote an Interpreter and then a Transpiler to convert Fortran to Javascript. BUT every time I was stuck with the Problem of passing variable by reference.
As you know in Fortran there is no syntax different between pass by reference or pass by value, all looks the same. However in Javascript pass by reference can only work, if the variable passed in an Object.
Fortran example code:
REAL FUNCTION PYTHAGORAS (A,B,K)
REAL A,B,K
K = 12 // E <=> K in GEOMETRIE()
PYTHAGORAS = SQRT(A**2+B**2)
END FUNCTION PYTHAGORAS
LOGICAL FUNCTION GEOMETRIE (H,B,D)
REAL H,B,D,E
B = 12
H = 7
// E is pass by reference, it's gonna be changed in PYTHAGORAS()
D = PYTHAGORAS(B, H, E)
GEOMETRIE = .TRUE.
END FUNCTION GEOMETRIE
I did a lot of research, but until now, I didn't find any useful result.
I was wondering, if there's any library out there to do the Job (Client-side / NodeJS). I can't imagine that until now, nobody tried to lose this Problem before.
A lazy hack would be to systematically embed the variables passed to the functions into a JS object:
function PYTHAGORAS(obj /* A B K */) {
obj.K = 12;
return Math.sqrt(obj.A * obj.A + obj.B * obj.B);
}
function GEOMETRIE(obj /* H B D */) {
var E;
obj.B = 12;
obj.H = 7;
obj.D = PYTHAGORAS({A:obj.B, B:obj.H, K:E});
return true;
}
var res = {H:0, B:0, D:0};
GEOMETRIE(res);
console.log(res);
Output:
Object { H=7, B=12, D=13.892443989449804 }
That may work reasonably well in the hypothesis of an automated translation of the original listing, and the resulting JS code would be easy to compare with the original FORTRAN code.
Now, it's going to be unnecessarily verbose and overloaded, as opposed to a complete manual rewrite.
EDIT : alternate version with truly separated variables
function PYTHAGORAS(A, B, K) {
K.val = 12;
return Math.sqrt(A.val * A.val + B.val * B.val);
}
function GEOMETRIE(H, B, D) {
var E = {};
B.val = 12;
H.val = 7;
D.val = PYTHAGORAS(B, H, E);
console.log('E = ' + E.val);
return true;
}
var H = {}
, B = {}
, D = {};
GEOMETRIE(H, B, D);
console.log('H = ' + H.val + ', B = ' + B.val + ', D = ' + D.val);
Output:
E = 12
H = 7, B = 12, D = 13.892443989449804