I’m using dynamic scoping to simulate pointers in JavaScript as follows:
var ptr = (function () {
var ptr = "(" + String(function (value) {
if (value === void 0) return upvalue;
else upvalue = value;
}) + ")";
return function (upvalue) {
return ptr.replace(/upvalue/g, upvalue);
};
}());
function swap(xptr, yptr) {
var t = xptr();
xptr(yptr());
yptr(t);
}
var x = 2;
var y = 3;
alert([x, y]);
swap(eval(ptr("x")), eval(ptr("y")));
alert([x, y]);
Is there any other way to achieve the same results (i.e. without resorting to eval)? It just seems like too much boilerplate.
Since the only thing you’re using the pointer for is to dereference it to access another variable, you can just encapsulate it in a property.
To create a pointer, pass the accessor methods which read and write the variable being pointed to.
To dereference a pointer, access its value. In other words, where in C you would write
*phere you writep.value.You can create multiple pointers to the same variable.
You can change what a pointer points to by simply overwriting the pointer variable with another pointer.
You can swap two variables through pointers.
Let’s swap the values of
iandjby using their pointers.You can create pointers to local variables.
Through the magic of closures, this gives you a way to simulate malloc.
Your magic trick works too: