realm-js icon indicating copy to clipboard operation
realm-js copied to clipboard

Add support for counters

Open kneth opened this issue 2 years ago • 19 comments

Problem

Realm Core supports a special case of integers: counters. Counters are in particular useful for synced Realms.

See also https://github.com/realm/realm-core/issues/5056

Solution

We'll be adding a new property type named "counter", which will use the "int" core type underneath but return instances of a Counter class instead of raw number.

declare class Counter {
  public get value(): number;
  public increment(by = 1);
  public decrement(by = 1);
  public set(value: number);

  // Implements https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf
  // this would allow using an instance of `Counter` to be coerced into a `number`.
  public valueOf(): number {
    return this.value;
  }
}

Because we cannot overload the increment operators ++, +=, -- and -= explicitly in JS (these simply call "set" / assignment underneath), we suggest throwing if these are used, to prevent users from relying on these operators which wouldn't use the proper counter semantics.

We discussed implementing a heuristic (if the setter is invoked just after the getter, perhaps users are performing a +=), but we wouldn't be able to distinguish that from a *= 2, in which case it would be misleading to use the counter semantics.

How important is this improvement for you?

No response

kneth avatar Nov 19 '21 09:11 kneth