🚨 Shai-Hulud Strikes Again:834 Packages Compromised.Technical Analysis →
Socket
Book a DemoInstallSign in
Socket

weakrefset

Package Overview
Dependencies
Maintainers
1
Versions
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

weakrefset

WeakRefSet, a weak set with access to the fields

latest
Source
npmnpm
Version
0.2.2
Version published
Maintainers
1
Created
Source

WeakSet but completed

Weak references are great, but nearly nothing truly uses it in javascript.

WeakRefSet.

Why not just use WeakSet? A native WeakSet is write only, you cant do things like .forEach or for (const value of set). The only thing it can be used for is seeing if it contains it.

Example

import {WeakRefSet} from "weakrefset";


class Clients {
    constructor(private readonly server: Server) {
    }

    doSomething() {

    }
}

class Server {
    clients = new WeakRefSet<Client>();
}

function test() {
    const server = new Server();
    const clientA = new Client(server);
    const clientB = new Client(server);
    server.clients.add(clientA).add(clientB);

    server.clients.forEach(client => client.doSomething());
}

test();

If this code was written with a normal new Set<Client>, everything would float forever in memory and never be cleaned. As both Client as Server have recursive references to each other. The magic of a weak reference will overcome this issue.

In the past, we would have demanded the user to call some server.close() function, but as we (java|type)script developers are lazy and not used with dealing with the garbage collector, we often forget.

With WeakRef the following happen

  • End of test(), reference all references to the client (clientA, clientB) get marked as deletable. As the variables are the only ones that count. The weak ref set is not counted as a reference
  • All Client instances get deleted
  • All server references are gone now, as test()'s server variable is gone, and so are all Client objects are gone
  • All memory usage of test() is fully and automatically cleaned up

What happens with a typical Set?

  • End of test(), references to the clientA and clientB are still holden in the Server instance.
  • clients instances still exists
  • server reference still exists in clients
  • all memory of test() is still in memory
  • memory leaked

FAQs

Package last updated on 04 Feb 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts