Hello, all
I started learning JavaScript but yesterday, but am already
stuck at implementing input/output parameters. As I
understand, they are not part of the language, yet I find
them very convenient for normal procedural programming. For
example, they allow returning a boolean flag and using
functions inside `if` tests, similar to the very convenient
TryParse() and TryGetValue() functions in C#:
TryParse: https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse TryGetValue: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.trygetvalue
Unfortunately for me, JavaScript seems to compensate the
lack of in/out parameters with much more complicated
functional and object-oriented mechanisms. I therefore have
tried to implement them myself, but have not come up with a
satisfactory solution. The examples below demonstrate a
function for integer division that stores the result in
variable and returns a boolean value indicating whether the
division was exact:
// for bi-direction in/out parameters, return a code that
// creates an anonymous object storing the the value *and*
// setter clousure:
function out_1(vn)
{ return "x => " + vn + " = x"; }
function int_div_1(a, b ,c)
{ var /*integer */ r; // ratio
var /*boolean */ x; // result is exact
r = Math.floor(a / b);
x = r * b === a;
c( r );
return x;
}
function out_2( vn, val, ret )
{ return `${vn} = ${val}, ${ret}`; }
function int_div_2(a, b, vn)
{ var /*integer */ r; // ratio
var /*boolean */ x; // result is exact
r = Math.floor(a / b);
x = r * b === a;
return out_2(vn, r, x);
}
{ let /*integer */ ratio;
let /*boolean */ exact;
exact = int_div_1(7, 3, eval(out_1("ratio")));
console.log(`7/3: ratio = ${ratio}; exact = ${exact}.`);
exact = int_div_1(6, 3, eval(out_1("r")));
console.log(`6/3: ratio = ${ratio}; exact = ${exact}.`);
exact = eval(int_div_2(7, 3, "ratio"));
console.log(`7/3: ratio = ${ratio}; exact = ${exact}.`);
exact = eval(int_div_2(6, 3, "ratio"));
console.log(`6/3: ratio = ${ratio}; exact = ${exact}.`);
}
Can you think of better way to emulate output parameters,
and preferable also bi-directional input/output parameters?
--
() ascii ribbon campaign -- against html e-mail
/\ http://preview.tinyurl.com/qcy6mjc [archived]
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 250 |
Nodes: | 16 (2 / 14) |
Uptime: | 83:45:52 |
Calls: | 5,510 |
Calls today: | 5 |
Files: | 11,668 |
Messages: | 5,086,179 |