Exercise 9: Storage Namespace Helper

Problem Statement

Function `createNamespace(prefix)` banao jo namespaced storage functions return kare. Example: const ns = createNamespace("app_"); ns.set("key", "value")

Sample Output:

const ns = createNamespace("app_");
ns.set("key", "value"); ns.get("key") => "value"

Solution

const createNamespace = (prefix) => ({
  set: (key, value) => localStorage.setItem(prefix + key, JSON.stringify(value)),
  get: (key) => {
    const item = localStorage.getItem(prefix + key);
    return item ? JSON.parse(item) : null;
  },
  remove: (key) => localStorage.removeItem(prefix + key)
});

Explanation

Overall Goal:

  • Namespaced storage functions create karna.

Real world:

  • Multi-app: namespace isolation.
  • Organization: key prefixing.