Code Logo

Object Collection with WeakSet

Published at25 Jul 2026
JavaScript Data Structures Hard 0 views
Like0

Write a JavaScript function that uses WeakSet to track objects that have been "processed". The function takes an object, adds it to a WeakSet, then checks if it's in the set. Return true if the object was successfully added (was not already in the set), or false if it was already there.

WeakSet is a JavaScript collection introduced in ES6 that stores objects with weak references. If there are no other references to an object stored in a WeakSet, the object can be garbage collected, and the entry is automatically removed. This makes WeakSet ideal for tracking metadata about DOM elements, caching, and preventing memory leaks.

Unlike Set, WeakSet can only store objects (not primitives). It has no .size property and is not iterable. The API is limited to .add(), .has(), and .delete(). The weak referencing behavior is unique to JavaScript among mainstream languages and enables efficient memory management for object-associated metadata.

Time complexity is O(1) for add, has, and delete operations. Space complexity is O(n) for n entries, but entries are automatically cleaned up when key objects are garbage collected, preventing unbounded memory growth.

Edge cases include adding the same object twice (second add returns the WeakSet itself but has() returns true), checking for objects not in the set (returns false), and ensuring non-object arguments are rejected (throws TypeError).

Example Input & Output

Example 1
Input
{x:10}
Output
true
Explanation

Another object

Example 2
Input
{val:42}
Output
true
Explanation

Yet another

Example 3
Input
{id:1}
Output
true
Explanation

Object with property

Example 4
Input
{name:'test'}
Output
true
Explanation

Object with name

Example 5
Input
{}
Output
true
Explanation

New object is added and tracked

Algorithm Flow

Recommendation Algorithm Flow for Object Collection with WeakSet
Recommendation Algorithm Flow for Object Collection with WeakSet

Solution Approach

function solution(obj) {
  var ws = new WeakSet();
  ws.add(obj);
  return ws.has(obj);
}

Best Answers

javascript - Approach 1
function solution(obj) {
  var ws = new WeakSet();
  ws.add(obj);
  return ws.has(obj);
}