← All tasksNode.js · Junior

Parse the Cookie header

The browser sends cookies in a single header: Cookie: session=abc123; theme=dark. Write parseCookies(header) that returns an object { session: "abc123", theme: "dark" }.

Spaces around names and values are trimmed, values are decoded with decodeURIComponent (a malformed value is kept as is), and quotes around a value are removed. Parts without = are skipped, and when a cookie repeats, the first one wins. An empty or missing header gives {}.

Tests (6)

  1. expect(parseCookies('session=abc123; theme=dark')).toEqual({ session: 'abc123', theme: 'dark' });
  2. expect(parseCookies('name=John%20Doe; city=Kyiv')).toEqual({ name: 'John Doe', city: 'Kyiv' });
  3. expect(parseCookies(undefined)).toEqual({});
    expect(parseCookies('')).toEqual({});
  4. expect(parseCookies('a=1;  b = 2 ;broken; c=')).toEqual({ a: '1', b: '2', c: '' });
  5. expect(parseCookies('id=1; id=2')).toEqual({ id: '1' });
  6. expect(parseCookies('token="x y"; bad=%E0%A4%A')).toEqual({ token: 'x y', bad: '%E0%A4%A' });