3

Is there a way to create WeakMap of any other weak references in Javascript for storing key value pairs where key is String/Number and value is Object.

The referencing would have to work something like this:

const wMap = new WeakRefMap();
const referencer = {child: new WeakRefMap()}
wMap.set('child', temp.child);
wMap.has('child'); // true
delete referencer.child
wMap.has('child'); //false     

I creating kind of a tree structure that holds track of references that are still used in the current scope.

I will do a lot of merging, and recursively cleaning up a deeply nested structure can be very inefficient for this use case.

Nabuska
  • 381
  • 8
  • 16

1 Answers1

1

You cannot catch a delete operation. What you could do would be encapsuling the data in another obj e.g.

function referenceTo(value){
 this.value=value;
}

So if this one reference is deleted, it cant be accessed anymore

var somedata=new referenceTo(5)
var anotherref=somedata;
//do whatever
delete somedata.value;
//cannot be accessed anymore
anotherref.value;//undefined
Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120
  • To my understanding that does not solve the issue of deleting nested structures when top one is deleted? ps. I fixed the example, the previous was invalid. I don't get it why es6 WeakMap does not take strings as keys and objects as values. Doesn't seem to add any value on everyday programming. – Nabuska Jul 19 '17 at 19:32
  • @nabuska yeah you may need to filter somewhen. – Jonas Wilms Jul 19 '17 at 19:38