Skip to content

Instantly share code, notes, and snippets.

@cleverdumb
Created November 27, 2022 19:30
Show Gist options
  • Save cleverdumb/b1058c73477c62c73ac26f2af3ce6cfb to your computer and use it in GitHub Desktop.
Save cleverdumb/b1058c73477c62c73ac26f2af3ce6cfb to your computer and use it in GitHub Desktop.
Guide on syncing variables, getters and setters

Introduction

You might want to sync two variables, and when one changes, the other changes accordingly (eg: the polar coordinate and cartesian coordinate of a vector). But as programmers we are lazy and we don't want to change each at a time with multiple lines of code. This is how to make it easy and convenient.

Goals

  • Be able to change and access these properties easily like normal variables or object properties
  • Be able to link as many variables as we want
  • No constant updating that would cause lag

Actually how

Let's try to do a simple case where two variables (x, y) need to be the same at the same time

We would use the getter and setter properties of classes, as it allows triggering functions when a variable is accessed or assigned.

So we create a class and create a new instance

class Object {
  constructor(x,y) {
    this.xPos = x;
    this.yPos = y;
  }
}

let object = new Object(10,10)
console.log(object.xPos, object.yPos) // 10 10

Then we create a setter for both the x position and the y position

class Object {
  constructor(x,y) {
    this.xPos = x;
    this.yPos = y;
  }
  set x(x) {
    this.xPos = x;
    this.yPos = x;
  }
  set y(y) {
    this.yPos = y;
    this.xPos = y;
  }
}

let object = new Object(10,10)
console.log(object.xPos, object.yPos) // 10 10

Now when we set one of the values, the other will change as well

object.x = 20;
console.log(object.xPos, object.yPos) // 20 20

object.y = 30;
console.log(object.xPos, object.yPos) // 30 30

But notice that when we access the variables we need to use xPos, which is not ideal.
So we need to use a getter

class Object {
  constructor(x,y) {
    this.xPos = x;
    this.yPos = y;
  }
  set x(x) {
    this.xPos = x;
    this.yPos = x;
  }
  set y(y) {
    this.yPos = y;
    this.xPos = y;
  }
  get x() {
    return this.xPos;
  }
  get y() {
    return this.yPos;
  }
}

let object = new Object(10,10)
console.log(object.xPos, object.yPos) // 10 10

Now we can access it with x and y

console.log(object.xPos, object.yPos, object.x, object.y) // 10 10 10 10

That's about it. x and y are now synced.
This way you can sync any number of variables.

-- Made for the JSM-community

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment