جواب «The Piggy Bank» چالش 6 از جلسهی 37
سؤال
این بار خودت از صفر و با نوع بنویس. یک قلک:
۱. coins یک آرایهی خالی از عددهاست.
۲. تابع drop یک سکه (number) میگیرد، آن را در coins میگذارد و جمع همهی سکهها را برمیگرداند.
۳. تابع report ورودی ندارد و متنی مثل 2 coins, 25 total برمیگرداند.
۴. اول برنامه: drop(5); و drop(20); و بعد show(report());
۵. با هر کلیک (press): یک سکهی ۱۰ بینداز و report() را نشان بده.
راهنما
const coins: number[] = []; بعد function drop(coin: number): number {. جمع را با یک حلقه روی coins حساب کن.
یک جواب درست
<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>
<button id="go" onclick="press()">Drop 10</button>
<pre id="out"></pre>
<script type="text/typescript">
const coins: number[] = [];
function sum(): number {
let all = 0;
for (const coin of coins) {
all = all + coin;
}
return all;
}
function drop(coin: number): number {
coins.push(coin);
return sum();
}
function report(): string {
return coins.length + " coins, " + sum() + " total";
}
function press(): void {
drop(10);
show(report());
}
drop(5);
drop(20);
show(report());
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن