0

So, I'm writing an API in Javascript. The ideal requirements include that it support a structure like so:

  • There are two classes: class Core, and class Public. Both have member id.
  • There cannot exist multiple instances of Core with the same id, but each must have a unique id; however, there may be any number of Public instances with the same id.
  • Public instances each have a single reference to the instance of class Core with the corresponding value for id.
  • Core instances should be garbage collected as soon as the last Public instance pointing to it is garbage collected.
  • Thus, when a new Public instance is created and given an id, it gathers and assigns its reference to either the existing Core instance, if one exists, or a new instance of Core if not.

and preferably (though not absolutely necessary):

  • When the last reference to a Core instance is dropped, a method on it is run (i.e., a destructor)

Also, as I'm writing this in ES6, WeakMaps, WebAssembly, and any other modern JS API is permissible in an answer.

Is this structure possible in Javascript? If so, what would be the structure of such an implementation? Or, is this completely out of the scope of Javascript's capability?

1 Answer 1

1

Is this structure possible in Javascript?

Yes it is. However you cannot intercept garbage collection in any way, if all the references to an object got lost it will disappear silently, no one will notice it. Therefore if you want to notice it, you have to cause it explicitly:

 class Reference {
   constructor(to) { 
     this.to = to; 
     to.link();
   }

   free() { 
     this.to.unlink(); 
     this.to = undefined;
   }
 }

 class Referenceable {
   constructor() {
     this.count = 0;
   }

   link() { this.count++ }
   unlink() {
     if(!(--this.count)) {
       // your last words
     }
   }
 }
1
  • 1
    True. I guess I hoped I could fight the obvious! :) As of now I've implemented it so that Core instances are cached in a queue with a max size. When Public instances need their respective Core, either the respective one is found and promoted to the top of the queue, or one is created and queued, dequeuing / deleting the oldest entry. I didn't want a queue, but I suppose it'll work for my purposes. Thanks!
    – Codesmith
    Dec 18, 2018 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.