mercredi 12 avril 2023

Is this a valid way of getting the "memory address" of an object in Javascript?

For my application, I basically need a way to convert a Javascript object to a unique number, such that it can be used as a seed in a deterministic random number generator. That is, given an object as the input to the random number generator, it will always return the same output.

This would be pretty easy if you could just get the memory address of an object and use that as the seed, but that doesn't seem possible. Another idea would be to use a Map, and then have an auto-incrementing number for each object insertion, but then you would have to somehow keep track of what was added so the map wouldn't balloon to ridiculous memory sizes after a while.

Then I thought, would a WeakMap work for something like this?

That is, doing something like this?

let incrementingID = 1;

function getIncrementingID() {
  incrementingID++;

  return incrementingID;
}

const weak = new WeakMap();

function getSeed(o) {
  const maybeSeed = weak.get(o);

  if (maybeSeed === undefined) {
    const newSeed = getIncrementingID();

    weak.set(o, newSeed);

    return newSeed;
  }

  return maybeSeed;
}

Then, given the same object, it will always produce a unique seed value, and also if the object ever goes out of scope, it should automatically be deleted from the map, right? So there will never be a memory leak?

This seems to work, but I've never used a WeakMap before and I'm not sure if this is a proper solution, or if there is a better way.




Aucun commentaire:

Enregistrer un commentaire