I used to be a C programmer & new in JavaScript and use pointers to swap elements of an array using
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
What will be the equivalent function of this in JavaScript?
I used to be a C programmer & new in JavaScript and use pointers to swap elements of an array using
void swap(int *a,int *b){
int temp=*a;
*a=*b;
*b=temp;
}
What will be the equivalent function of this in JavaScript?
You can transform your array from [1,2,3]
to [{val: 1}, {val:2}, {val: 3}]
and use such approach:
const swap = (a, b) => {
const val = a.val;
a.val = b.val;
b.val = val;
}
Array contains the same references with new vals.
You can implement some of pointer logic using ArrayBuffer and its views like Uint8Array with helpers like TextEncoder.
var memory = new TextEncoder().encode("HelloWorld");
// create pointers in memory
var H = new Uint8Array(memory.buffer, 0, 1);
var W = new Uint8Array(memory.buffer, 5, 1);
// create string from byte array
const toString = buf => String.fromCharCode.apply(null, buf);
// swap two bytes in memory
function swap(a, b) {
[a[0],b[0]] = [b[0],a[0]];
}
swap(H, W);
console.log(toString(memory)); // WelloHorld
In JavaScript you can pass the references of variables by grouping them in an object. So let's say you have two variables x and y... They have to be enclosed in an object.
const values = {
x : 1,
y : 3
}
We can pass them as one object to the swap function:
swap(values)
And inside the function we can swap them like so:
function swap (obj) {
let temp = obj.x
obj.x = obj.y
obj.y = temp
}
You can read more about it here
this method has a flaw though as you have to pass the values named x and y to the swap function. We can tweak the function to be more dynamic as follows:
function swap (obj) {
let temp = obj[Object.keys(obj)[0]]
obj[Object.keys(obj)[0]] = obj[Object.keys(obj)[1]]
obj[Object.keys(obj)[1]] = temp
}
This code snippet works as an equivalent :
function swap(arr, from, to) {
arr.splice(from, 1, arr.splice(to, 1, arr[from])[0]);
}
let a = 1;
let b = 2;
console.log("Before Swap");
console.log("value a: " + a);
console.log("value b: " + b);
[a, b] = [b, a];
console.log("After swap");
console.log("value a: " + a);
console.log("value b: " + b);
You can use Destructuring Assignment in order to swap a value. I also just learned it. Please correct me if im wrong, im also new to JavaScript