Exercise 12: Get Storage Value with Version Check

Problem Statement

Function `getVersioned(key, expectedVersion)` banao jo value get kare aur version match kare. Example: getVersioned("data", "v1") => value or null if version mismatch

Sample Output:

getVersioned("data", "v1") => {x: 1} (if version matches)
getVersioned("data", "v2") => null (if mismatch)

Solution

const getVersioned = (key, expectedVersion) => {
  const item = JSON.parse(localStorage.getItem(key) || "null");
  if (!item || item.version !== expectedVersion) return null;
  return item.value;
};

Explanation

Overall Goal:

  • Version check ke saath value get karna.

Real world:

  • Data validation: version checks.
  • Migration: version compatibility.