جواب «The Safe Profile» چالش 6 از جلسهی 39
سؤال
یک پروفایل بازیکن بساز که هم یادش بماند و هم از دادهی قدیمی نترسد. دکمهی Old data و تابع old آمادهاند: یک پروفایل قدیمی بدون level نگه میدارند.
۱. interface Profile با name (متن) و level (عدد).
۲. نگهبان نوع: function isProfile(value: unknown): value is Profile. بررسی کن شیء است، null نیست، name متن است و level عدد.
۳. با salam.load("profile") بخوان. اگر isProfile گفت بله، همان؛ وگرنه { name: "Guest", level: 1 }. اسمش را profile بگذار.
۴. اول برنامه بنویس Guest: level 1 (اسم، : level و عدد).
۵. تابع levelUp: یکی به level اضافه کن، پروفایل را زیر اسم "profile" نگه دار و همان خط را دوباره نشان بده.
راهنما
نگهبان: return typeof value === "object" && value !== null && "name" in value && typeof value.name === "string" && "level" in value && typeof value.level === "number";
یک جواب درست
<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="up" onclick="levelUp()">Level up</button>
<button id="old" onclick="old()">Old data</button>
<pre id="out"></pre>
<script type="text/typescript">
interface Profile {
name: string;
level: number;
}
function isProfile(value: unknown): value is Profile {
return typeof value === "object" && value !== null
&& "name" in value && typeof value.name === "string"
&& "level" in value && typeof value.level === "number";
}
const raw = salam.load("profile");
const profile: Profile = isProfile(raw) ? raw : { name: "Guest", level: 1 };
function levelUp(): void {
profile.level = profile.level + 1;
salam.save("profile", profile);
show(profile.name + ": level " + profile.level);
}
function old(): void {
salam.save("profile", { name: "Sara" });
show("Old data saved");
}
show(profile.name + ": level " + profile.level);
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن