FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

useSet

15mins

Implement a helper useSet(initialState) that manages a JavaScript Set with extra utility methods.

Normally, when using a plain Set, you need to clone/mutate it before reassigning.
useSet makes it easier by providing built-in methods to manage the set.

Your task: Implement useSet(initialState) that:

  • Accepts an initial Set of items.
  • Returns an object with the following:
    • set: the current Set of items.
    • add(item): adds item to the set.
    • remove(item): removes item from the set.
    • toggle(item): adds item if it doesn’t exist, removes it if it does.
    • reset(): resets the set back to the initial state.
    • clear(): clears the entire set.

Example

const mySet = useSet(new Set(["hello"])); mySet.add("world"); console.log(mySet.set); // Set { "hello", "world" } mySet.toggle("hello"); console.log(mySet.set); // Set { "world" } mySet.reset(); console.log(mySet.set); // Set { "hello" } mySet.clear(); console.log(mySet.set); // Set {}

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests