بتل کد Battle Codeدارد باز می‌شود…

جواب «The Top Score» چالش 6 از جلسه‌ی 18

سؤال

از صفر دو تابع بنویس:
۱. best(list: number[]): number | null بزرگ‌ترین عدد آرایه را برمی‌گرداند. اگر آرایه خالی بود، null.
۲. tell(list: number[]): string از best استفاده می‌کند: اگر جواب null بود No scores را برمی‌گرداند، وگرنه Best: و آن عدد را.

بعد این دو خط را نشان بده:
tell([12, 20, 7]) ← Best: 20
tell([]) ← No scores

راهنما

در best: اول if (list.length === 0) { return null; }، بعد با یک حلقه بزرگ‌ترین را پیدا کن. در tell: const b = best(list); و if (b === null) { return "No scores"; }

یک جواب درست

<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>

<pre id="out"></pre>

<script type="text/typescript">
function best(list: number[]): number | null {
  if (list.length === 0) {
    return null;
  }
  let top = list[0];
  for (const n of list) {
    if (n > top) {
      top = n;
    }
  }
  return top;
}

function tell(list: number[]): string {
  const b = best(list);
  if (b === null) {
    return "No scores";
  }
  return "Best: " + b;
}

show(tell([12, 20, 7]));
show(tell([]));
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن