تمرين إعادة البناء
CSV Row Parser
أعد كتابة محلل CSV صغير في TypeScript يحوّل الصفوف إلى سجلات typed.
typescript
~14 دقيقة
متوسط
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
interface StudentScore {
name: string;
subject: string;
score: number;
}
function parseCsvLine(line: string): string[] {
return line.split(",").map((cell) => cell.trim());
}
function parseStudentScore(line: string): StudentScore {
const [name, subject, scoreText] = parseCsvLine(line);
const score = Number(scoreText);
if (!name || !subject || !Number.isFinite(score)) {
throw new Error(`Invalid row: ${line}`);
}
return { name, subject, score };
}
function averageScore(rows: StudentScore[]): number {
const total = rows.reduce((sum, row) => sum + row.score, 0);
return rows.length === 0 ? 0 : total / rows.length;
}
const csvRows = ["Noura,TypeScript,95", "Ali,TypeScript,88", "Maha,TypeScript,91"];
const scores = csvRows.map(parseStudentScore);
console.log(scores);
console.log(`Average: ${averageScore(scores).toFixed(1)}`);اكتب هنا