JSFiddle - React, Tailwind, and code Playground

by Michael Dibbets

HTML

Please open your javascript console to see the output.

JavaScript

// generic storage. ALL idHolder objects go in here, as a referrence copy
generic = [];
// the "real" registry.
registry = [];
// All we hold is an id.
function idHolder(id) {
    // Save in generic registry so we can see what happens to values
    window.generic.push(this);
    // Check and run if we have idHolder types in the registry
    for(c=0;c<registry.length;c++) {
        // Are we the same family?
        if(registry[c] instanceof idHolder) {
            // Do we want the same id?
            if(registry[c].id === id) {
               // WE MERGE! Fusion HO!
               return registry[c];
            }
        }
    }
    // I LIVE!
    this.id = id;
    // Saving myself
    this.registryID = window.registry.push(this)-1;
}
idHolder.prototype.destroy = function() { 
    // cleanup function. call this before nulling the variables so it deregisters fromt the registry. Otherwise you have a leak or you need to run an intermittend cleanup function to clean the registry array;
    window.registry[this.registryID] = null;
    this.id = null;
    this.registryid = null;
}
a = new idHolder(1);
b = new idHolder(2);
c = new idHolder(3);
// pushing fake object to trick test
registry.push({id:1});
// d should up with same instance as a; leaving a empty object in memory that will get garbage collected.
d = new idHolder(1);
console.log("Generic array. this has all entries that called via new.");
console.log(generic);
console.log("Registry. this should contain only 4 entries. one bogus, three idHolder");
console.log(registry);
// setting id to 10 of d. this should change a.
d.id = 10;
console.log("d was changed to 10. a is now : "+a.id);
console.log("Destroying a, logging a and d");
a.destroy();
// The last men standing...
console.log(a);
console.log(d);
console.log("nulling a & d. only references to these objects should be in the generic array");
a = null;
b = null;
console.log(a);
console.log(d);
console.log(registry);
console.log("Logging generic array. Don't...