Search code examples
javascriptnode.jsfirefoxgoogle-chromev8

Reference indexed collection in Javascript


I search a way to get in Javascript an object which index by reference.

something like:

var myRefMap = new RefMap();

var a = [{}, [], function () {}];

myRefMap.set(a[0], true);
myRefMap.set(a[1], { hello: 'world' });
myRefMap.set(a[2], 42);

myRefMap.has(a[0]); // true
myRefMap.has(a[1]); // true
myRefMap.has(a[2]); // true

myRefMap.has({});             // false
myRefMap.has([]);             // false
myRefMap.has(function () {}); // false

I need this object in order to optimize and avoid an actual heavy array search, during tree browsing within circulars references.

Thanks,


Solution

  • One basic way to do this, provided all the stored values are objects would be something like:

    (function () {
        var instCount = 0;
        self.RefMap = function () {
            instCount ++;
            var propName = '__RefMap' + instCount + '__';
            this.has = function (o) {
                return propName in o;
            };
            this.set = function (o) {
                o[propName] = true;
            }
            this.remove = function (o) {
                delete o[propName];
            }
        }
    }());
    
    //then use it like
    var myRefMap = new RefMap();
    

    Edit: Arrays and functions are objects too. And you can use Object.defineProperty to hide the "marking" property, depending on the browsers you target.