So, I'm writing an API in Javascript. The ideal requirements include that it support a structure like so:
class Core
, and class Public
. Both have member id
.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.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):
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?
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
}
}
}