npm.io
0.2.2 • Published 3 months ago

weak-id

Licence
MIT
Version
0.2.2
Deps
1
Size
5 kB
Vulns
0
Weekly
0

weak-id

build status Coverage Status

Social Media Photo by Mario Amé on Unsplash

A utility to generate unique ids for weak references.

import weakID from 'weak-id';

const wid = weakID(id => {
  console.log(id, 'collected');
});

let obj = {};
let [id, unknown] = wid(obj);

console.assert(unknown);
console.assert(id === wid(obj)[0]);
console.assert(!wid(obj)[1]);

obj = null;
// the log will happen

To have a reliable i32 value and ensure the next id will be actually a 32bit integer, you can also directly import the i32 variant:

import i32 from 'weak-id/i32';

// initialize a function that
// will always return a 32bit integer
const next = i32();
// i32(42) to start from 42 as initial value

console.assert(next() === 0);
console.assert(next() === 1);
// ...

Keywords