File size: 5,397 Bytes
f91a684
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
import type { CodingQuestion } from '@/data/codingQuestions';
import { apiFetch } from '@/lib/authClient';

type DSADifficulty = CodingQuestion['difficulty'];
type StarterCode = CodingQuestion['starterCode'];

export type DSAMongoQuestion = {
  id: string;
  source?: string;
  questionNumber: number;
  title: string;
  difficulty: string;
  category: string;
  topics: string[];
  companies?: string[];
  hint?: string;
  problemStatement: string;
  examples?: {
    input: string;
    expectedOutput: string;
    explanation?: string;
  }[];
  constraints?: string[];
};

type DSAQuestionsResponse = {
  questions?: DSAMongoQuestion[];
};

const emptyStarterCode: StarterCode = {
  javascript: '',
  python: '',
  cpp: '',
  java: '',
  go: '',
};

function splitTopLevel(value: string) {
  const parts: string[] = [];
  let current = '';
  let depth = 0;
  let quote: '"' | "'" | null = null;
  let escaped = false;

  for (const char of value) {
    if (escaped) {
      current += char;
      escaped = false;
      continue;
    }

    if (char === '\\') {
      current += char;
      escaped = true;
      continue;
    }

    if (quote) {
      current += char;
      if (char === quote) quote = null;
      continue;
    }

    if (char === '"' || char === "'") {
      current += char;
      quote = char;
      continue;
    }

    if (char === '[' || char === '{' || char === '(') depth += 1;
    if (char === ']' || char === '}' || char === ')') depth = Math.max(0, depth - 1);

    if (char === ',' && depth === 0) {
      parts.push(current.trim());
      current = '';
      continue;
    }

    current += char;
  }

  if (current.trim()) parts.push(current.trim());
  return parts;
}

function parseExampleValue(raw: string): unknown {
  const value = raw.trim().replace(/^(?:Input|Output):\s*/i, '');
  if (!value) return '';

  const jsonLike = value
    .replace(/\bTrue\b/g, 'true')
    .replace(/\bFalse\b/g, 'false')
    .replace(/\bNone\b/g, 'null')
    .replace(/\bNULL\b/g, 'null')
    .replace(/\bnull\b/g, 'null')
    .replace(/'/g, '"');

  try {
    return JSON.parse(jsonLike);
  } catch {
    if (/^-?\d+(?:\.\d+)?$/.test(value)) return Number(value);
    if (/^(true|false)$/i.test(value)) return value.toLowerCase() === 'true';
    return value.replace(/^["']|["']$/g, '');
  }
}

function parseExampleParams(input: string) {
  const value = input.trim().replace(/^Input:\s*/i, '');
  if (!value) return [];

  const parts = splitTopLevel(value);
  const assignments = parts
    .map((part) => part.match(/^[A-Za-z_]\w*\s*=\s*([\s\S]+)$/)?.[1])
    .filter((part): part is string => Boolean(part));

  if (assignments.length > 0) {
    return assignments.map(parseExampleValue);
  }

  return [parseExampleValue(value)];
}

function normalizeDifficulty(value: string): DSADifficulty {
  const normalized = value.trim().toLowerCase();
  if (normalized === 'medium' || normalized === 'med.') return 'Medium';
  if (normalized === 'hard') return 'Hard';
  return 'Easy';
}

function formatDSADescription(question: DSAMongoQuestion) {
  const sections = [question.problemStatement.trim()].filter(Boolean);

  if (question.examples?.length) {
    sections.push(
      [
        'Examples:',
        ...question.examples.map((example, index) => {
          const lines = [`${index + 1}. Input: ${example.input}`];
          if (example.expectedOutput) lines.push(`   Output: ${example.expectedOutput}`);
          if (example.explanation) lines.push(`   Explanation: ${example.explanation}`);
          return lines.join('\n');
        }),
      ].join('\n'),
    );
  }

  if (question.constraints?.length) {
    sections.push(['Constraints:', ...question.constraints.map((constraint) => `- ${constraint}`)].join('\n'));
  }

  if (question.hint) {
    sections.push(`Hint: ${question.hint}`);
  }

  if (question.companies?.length) {
    sections.push(`Asked by: ${question.companies.join(', ')}`);
  }

  return sections.join('\n\n');
}

function toTestCases(question: DSAMongoQuestion): CodingQuestion['testCases'] {
  return (question.examples ?? []).map((example) => ({
    input: example.input,
    output: example.expectedOutput,
    params: parseExampleParams(example.input),
    expected: parseExampleValue(example.expectedOutput),
  }));
}

export function mapDSAQuestionToCodingQuestion(question: DSAMongoQuestion): CodingQuestion {
  return {
    id: question.id || `dsa-${question.questionNumber}`,
    title: question.title,
    difficulty: normalizeDifficulty(question.difficulty),
    category: question.category || question.topics?.[0] || 'DSA',
    companies: question.companies ?? [],
    description: formatDSADescription(question),
    starterCode: emptyStarterCode,
    testCases: toTestCases(question),
    hiddenTestCases: [],
    solution: {
      javascript: '',
      python: '',
      cpp: '',
      java: '',
      go: '',
      explanation: question.hint || 'A full solution is not available for this MongoDB question yet.',
    },
  };
}

export async function fetchDSAQuestions(): Promise<CodingQuestion[]> {
  const res = await apiFetch('/api/dsa/questions');
  if (!res.ok) {
    const text = await res.text();
    throw new Error(text.trim() || `Failed to fetch DSA questions (${res.status})`);
  }

  const data = (await res.json()) as DSAQuestionsResponse;
  return (data.questions ?? []).map(mapDSAQuestionToCodingQuestion);
}