تمرين إعادة البناء
Array Utilities
أعد كتابة دوال TypeScript عامة للتعامل مع المصفوفات.
typescript
~12 دقيقة
مبتدئ
أعد بناء الكود
Rebuild
هذا هو الكود. اكتبه بنفسك.
الكود المرجعي
function first<T>(items: T[]): T | undefined {
return items[0];
}
function unique<T>(items: T[]): T[] {
return [...new Set(items)];
}
function groupBy<T, K extends string | number>(items: T[], getKey: (item: T) => K): Record<K, T[]> {
return items.reduce(
(groups, item) => {
const key = getKey(item);
groups[key] = groups[key] ?? [];
groups[key].push(item);
return groups;
},
{} as Record<K, T[]>,
);
}
const names = ["Ali", "Sara", "Ali", "Noura"];
const scores = [82, 91, 82, 75];
console.log(first(names));
console.log(unique(scores));
console.log(groupBy(names, (name) => name.length));اكتب هنا