ရိုးရိုးလေး ရှင်းပြမယ်
ရိုးရိုးလေး ရှင်းရရင်
Exercise 1 မှာ concept တစ်ခုကို တစ်ကြိမ်မှာ တစ်ခုပဲ လေ့ကျင့်ခဲ့ပါတယ်။ ဒီ set မှာတော့ Advanced Concepts၊ OOP နဲ့ Async JavaScript chapter တွေက concept နှစ်ခုကို ပေါင်းသုံးရပါတယ်။ ဥပမာ closure နဲ့ higher-order function၊ async/await နဲ့ loop ပါ။
ဟင်းချက်တာနဲ့ တူပါတယ်။ ကြက်သွန်ကြော်တတ်တာနဲ့ ထမင်းချက်တတ်တာ သီးသန့်ဆိုရင် လွယ်ပါတယ်။ ဒါပေမယ့် နှစ်ခုကို တစ်ပြိုင်နက် ချက်ရင် အချိန်ညှိရပါတယ်၊ တစ်ခုခု တူးသွားတတ်ပါတယ်။ Code မှာလည်း concept တစ်ခုချင်းက ရှင်းပေမယ့် ထိတွေ့တဲ့ နေရာမှာ bug တွေ ပေါ်ပါတယ်။ Solution မကြည့်ခင် ၁၀-၁၅ မိနစ် ကိုယ်တိုင် စဉ်းစားပါ။ ဒီလို challenge တွေက interview ပြင်ဆင်ဖို့လည်း ကောင်းပါတယ်။
Problem → Why → Solution
ပြဿနာ: concept တစ်ခုချင်း မှန်ပေမယ့် ပေါင်းလိုက်ရင် ပျက်တာ
အောက်က code ကို ကြည့်ပါ။ Object literal၊ arrow function၊ async function၊ try/catch အားလုံးက syntax အရ မှန်ပါတယ်။ ဒါပေမယ့် ပေါင်းလိုက်တဲ့အခါ bug သုံးခု ပေါ်ပါတယ်။
ပထမ၊ count က public property ဖြစ်လို့ ဘယ် code မဆို counter.count = 999 လို့ ပြင်နိုင်ပါတယ်။ ဒုတိယ၊ increment က arrow function ဖြစ်လို့ this က counter object မဟုတ်ပါဘူး။ Arrow function က this ကို အပြင်ဘက်ကနေ ယူလို့ module ထဲမှာ undefined ဖြစ်ပြီး TypeError တက်ပါတယ်။ Classic script မှာဆိုရင် global object ပေါ်က count ကို NaN ဖြစ်အောင် ပြင်သွားပါတယ်။ တတိယ၊ loadUser() က await မပါဘဲ promise ကို return လုပ်လို့ rejection က try ထဲမှာ မဖြစ်ဘဲ function ပြီးမှ ဖြစ်ပါတယ်။ catch block ကို ဘယ်တော့မှ မရောက်ဘဲ unhandled rejection ဖြစ်သွားပါတယ်။
const counter = {
count: 0, // anyone can write counter.count = 999
increment: () => this.count++, // arrow function: `this` is not counter
};
async function loadUser(id) {
try {
return fetchUserData(id); // no await: a rejection skips this catch
} catch (err) {
return "Could not load user";
}
}
console.log(loadUser(0)); // Promise { <pending> } - and later an unhandled rejectionဘာကြောင့် ဒီ bug တွေက ရှာရခက်တာလဲ
Concept တစ်ခုချင်း သင်တုန်းက ဥပမာတွေမှာ ဒီ trap တွေ မပေါ်ခဲ့ပါဘူး။ this ကို method syntax နဲ့ပဲ သင်ခဲ့ပြီး try/catch ကိုလည်း synchronous code နဲ့ပဲ သင်ခဲ့လို့ပါ။ Bug က concept နှစ်ခုရဲ့ စည်းမျဉ်းတွေ ထိတွေ့တဲ့ နေရာမှာ ရှိနေလို့ code ကို line တစ်ကြောင်းချင်း ဖတ်ရုံနဲ့ မမြင်ရပါဘူး။
Core concept: concept တွေ ထိတွေ့တဲ့ နေရာကို စစ်ပါ
Advanced challenge တစ်ခုကို စမရေးခင် မေးခွန်းလေးခု မေးပါ။ (၁) State ကို ဘယ်သူ ပိုင်လဲ၊ အပြင်က ပြင်ခွင့်ရှိလား။ (၂) ဘယ် code က synchronous၊ ဘယ်ဟာက asynchronous လဲ။ (၃) Error တစ်ခု ဖြစ်ရင် ဘယ်လမ်းကြောင်းအတိုင်း သွားမလဲ၊ ဘယ်သူ ဖမ်းမလဲ။ (၄) this က ဘာကို ညွှန်နေလဲ။ ဒီမေးခွန်းတွေရဲ့ အဖြေက concept တစ်ခုစီရဲ့ စည်းမျဉ်းတွေကနေ လာပါတယ်။
| Concept | ပေးတဲ့ အကျိုး | ထိတွေ့ရာမှာ trap |
|---|---|---|
| Closure | Function ပြီးသွားလည်း variable ကို မှတ်ထားတယ် | Object property နဲ့ ရေးရင် private မဖြစ်တော့ဘူး |
| Static method | Instance မလိုဘဲ class ပေါ်က ခေါ်တယ် | this က instance မဟုတ်ဘဲ class ဖြစ်တယ် |
| async/await | Promise ကို synchronous ပုံစံ ဖတ်ရတယ် | try ထဲမှာ await မပါရင် catch က မဖမ်းဘူး |
| Arrow function | တိုတောင်းပြီး this ကို အပြင်က ယူတယ် | Object method အဖြစ် သုံးရင် this မှားတယ် |
Execution order ကိုလည်း သတိထားရပါမယ်။ Synchronous code အားလုံး အရင် run ပြီးမှ setTimeout callback တွေနဲ့ await နောက်က code တွေ ဆက် run ပါတယ်။ Example မှာ loadUser() ကို နောက်ဆုံးမှ await လုပ်ထားလို့ output အစီအစဉ်က code အစီအစဉ်အတိုင်း ဖြစ်ပါတယ်။ await မပါဘဲ loadUser(7) ကို ခေါ်ရုံဆိုရင် counter နဲ့ products line တွေ အရင်ထွက်ပြီး user line တွေက 50ms နောက်မှ ထွက်ပါလိမ့်မယ်။
နောက်ဆုံးအနေနဲ့ correctness ကို အရင် ဦးစားပေးပါ။ Code ကို တိုအောင်၊ မြန်အောင် ပြင်တာက success နဲ့ failure case နှစ်မျိုးလုံး မှန်ပြီးမှ လုပ်ရမယ့် အလုပ်ပါ။
Failure လမ်းကြောင်းကိုလည်း တကယ် run ပါ
Async task တိုင်းအတွက် အောင်တဲ့ call တစ်ခုနဲ့ ပျက်တဲ့ call တစ်ခုကို run ကြည့်ပြီးမှ ပြီးပြီလို့ သတ်မှတ်ပါ။ Example က user 7 နဲ့ user 0 နှစ်ခုလုံးကို load လုပ်တာ ဒါကြောင့်ပါ။ Success path ကိုပဲ မြင်ဖူးတဲ့ solution ဆိုရင် catch block ထဲမှာ ဘယ်သူမှ မ run ဖူးသေးတဲ့ typo တစ်ခု ပုန်းနေနိုင်ပါတယ်။ Error message ကိုလည်း ဖတ်ကြည့်ပါ၊ user ကို တကယ် ဘာဖြစ်လဲ ပြောပြနိုင်ရပါမယ်။
- State ကို ဘယ်သူ ပိုင်လဲ မေး
- Sync နဲ့ async ကို ခွဲ
- Error ဘယ်ကို သွားလဲ လိုက်ကြည့်
- this က ဘာလဲ စစ်
ဒီ မေးခွန်းလေးခုကို code မရေးခင် ဖြေနိုင်ရင် challenge ရဲ့ ထက်ဝက်ကျော်ကို ဖြေပြီးသားပါ။
အခြေခံ ပုံစံ
function makeThing() { let state = 0; return { change: () => ++state }; } // closure
class Model {
static compare(a, b) { return a.value >= b.value ? a : b; } // on the class itself
}
async function load(id) {
try { return await request(id); } // await INSIDE try, or catch never sees it
catch (err) { return fallback(err); }
}
const names = list.filter(({ key }) => test(key)).map(({ name }) => name);ပုံစံ လေးမျိုးပါ။ Closure က private state ကို ပိုင်တယ်၊ static method က class ပေါ်မှာ ရှိတယ်၊ await ကို try ထဲမှာ ထားတယ်၊ filter/map callback မှာ လိုတဲ့ field ကိုပဲ destructure လုပ်တယ်။
Task 1-4 ရဲ့ အဖြေများ
Task လေးခုက ဒီလိုပါ။ Task 1: closure နဲ့ increment()၊ decrement()၊ reset() ပါတဲ့ createCounter() ကို ရေးပါ၊ count ကို အပြင်က တိုက်ရိုက် မမြင်ရပါစေနဲ့။ Task 2: name နဲ့ age ပါတဲ့ Person class မှာ အသက်ကြီးသူကို ပြန်ပေးတဲ့ static compareAge(p1, p2) ကို ထည့်ပါ။ Task 3: setTimeout နဲ့ simulate လုပ်ထားတဲ့ fetchUserData(id) ကို async/await နဲ့ try/catch သုံးပြီး ခေါ်ပါ။ Task 4: product array ကနေ 1000 အောက် ဈေးရှိတဲ့ နာမည်တွေကို destructuring နဲ့ filter/map ချိတ်ပြီး ထုတ်ပါ။
// Task 1: a closure keeps count private
function createCounter() {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
reset: () => (count = 0),
};
}
// Task 2: a static method belongs to the class, not to each person
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
static compareAge(p1, p2) {
return p1.age >= p2.age ? p1 : p2; // a tie returns the first person
}
}
// Task 3: a simulated request that can fail
function fetchUserData(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id <= 0) reject(new Error("Invalid user id"));
else resolve({ id, name: "User " + id });
}, 50);
});
}
async function loadUser(id) {
try {
const user = await fetchUserData(id);
return `Loaded ${user.name}`;
} catch (err) {
return `Could not load user ${id}: ${err.message}`;
}
}
// Task 4: destructure inside filter and map
const products = [
{ name: "Pen", price: 500 },
{ name: "Bag", price: 15000 },
{ name: "Book", price: 800 },
];
const counter = createCounter();
console.log(counter.increment(), counter.increment(), counter.decrement());
console.log("after reset:", counter.reset(), "| count visible?", counter.count);
const older = Person.compareAge(new Person("Mya", 31), new Person("Ko Ko", 28));
console.log("older:", older.name);
const cheapNames = products
.filter(({ price }) => price < 1000)
.map(({ name }) => name);
console.log("cheap:", JSON.stringify(cheapNames));
console.log(await loadUser(7));
console.log(await loadUser(0));Code ကို တစ်ပိုင်းချင်း ရှင်းပြမယ်
- Pre-increment returns the new value
increment: () => ++count,++count က တိုးပြီးသား value ကို ပြန်ပေးလို့ ပထမ call က 1၊ ဒုတိယက 2 ပါ။ count++ လို့ ရေးရင် မတိုးခင် value (0၊ 1) ကို ပြန်ပေးပါတယ်။ Arrow function ဖြစ်ပေမယ့် this ကို မသုံးလို့ ပြဿနာ မရှိပါဘူး။
- Privacy through the closure
console.log("after reset:", counter.reset(), "| count visible?", counter.count);Return လုပ်တဲ့ object မှာ count ဆိုတဲ့ property မရှိလို့ counter.count က undefined ပါ။ count ကို ပြောင်းနိုင်တာ function သုံးခုပဲ ရှိပါတယ်။
- A static method decides the tie
return p1.age >= p2.age ? p1 : p2; // a tie returns the first personPerson.compareAge() လို့ class ပေါ်ကနေ ခေါ်ပါတယ်။ အသက်တူရင် ဘယ်သူ ပြန်ပေးမလဲ ဆိုတာကို >= နဲ့ ရှင်းရှင်း ဆုံးဖြတ်ထားပြီး comment မှာ ရေးထားပါတယ်။
- await inside try
const user = await fetchUserData(id);await က try block ထဲမှာ ရှိလို့ id 0 အတွက် reject ဖြစ်တဲ့အခါ catch ကို ရောက်ပြီး "Could not load user 0" ကို ပြန်ပေးပါတယ်။
- Destructuring in the callbacks
.filter(({ price }) => price < 1000)Callback parameter မှာ price ကိုပဲ ထုတ်ယူလို့ product.price လို့ ထပ်ခါထပ်ခါ ရေးစရာ မလိုပါဘူး။ map() ကလည်း name ကိုပဲ ယူပြီး ["Pen","Book"] ကို ပြန်ပေးပါတယ်။
1 2 1
after reset: 0 | count visible? undefined
older: Mya
cheap: ["Pen","Book"]
Loaded User 7
Could not load user 0: Invalid user idExample ရဲ့ timeline ကို ဆွဲကြည့်ပါ
Async ပါတဲ့ challenge တစ်ခုမှာ output အစီအစဉ်ကို မသေချာရင် အချိန်က ဘယ်ကနေ ညာကို စီးဆင်းတဲ့ timeline တစ်ခု ဆွဲပါ။ Synchronous line တွေကို ပထမ အုပ်စုမှာ ထားပြီး setTimeout callback တွေနဲ့ await နောက်က code တွေကို delay အလိုက် နောက်မှာ ထားပါ။ အောက်က diagram က lesson example ကို ဒီနည်းနဲ့ ဆွဲထားတာပါ။ loadUser(0) ရဲ့ timer က loadUser(7) ပြီးမှ စတာကို သတိထားပါ၊ await နှစ်ခုက တစ်ခုပြီးမှ တစ်ခု run လို့ပါ။
Execution timeline of the worked example
----------------------------------------
time 0ms --------------------- 50ms --------------------- 100ms
| | |
sync: counter, older, cheap | |
loadUser(7) starts a timer | |
"Loaded User 7" |
loadUser(0) starts a timer |
reject
catch -> messageလက်တွေ့ project တွေမှာ
လက်တွေ့ project တွေမှာ
ဒီ challenge တွေထဲက ပုံစံတွေက library တွေထဲမှာ နေ့တိုင်း တွေ့ရပါတယ်။ memoize လို closure + higher-order function ပေါင်းစပ်မှုက တွက်ရခက်တဲ့ ရလဒ်တွေကို cache လုပ်ဖို့ သုံးပါတယ်။ retry လို async loop ကတော့ ခဏခဏ ပျက်တတ်တဲ့ network request တွေကို ပြန်ကြိုးစားဖို့ သုံးပါတယ်။ Static method တွေကို User.fromJSON(data) လို factory method တွေအဖြစ် သုံးလေ့ရှိပါတယ်။
Team project တွေမှာ challenge တစ်ခုချင်းစီ (ဒါမှမဟုတ် feature တစ်ခုချင်းစီ) အတွက် success test၊ failure test နဲ့ cleanup ကို စဉ်းစားပါ။ Timer တွေကို clearTimeout နဲ့ ရှင်းပြီးပြီလား၊ event listener တွေကို ဖယ်ပြီးပြီလား၊ promise တိုင်းကို return ဒါမှမဟုတ် await လုပ်ထားလား ဆိုတာကို code review မှာ စစ်လေ့ရှိပါတယ်။ ESLint ရဲ့ no-floating-promises လို rule တွေက (TypeScript ESLint plugin မှာ ပါပါတယ်) await မေ့တာကို bug က user ဆီ မရောက်ခင် ကတည်းက အလိုအလျောက် ဖမ်းပေးနိုင်ပါတယ်။
အမှားများ
ဖြစ်လေ့ရှိတဲ့ အမှားများ
try ထဲမှာ await မပါဘဲ promise ကို return လုပ်တာ
return fetchUserData(id) လို့ ရေးရင် function က promise ကို ချက်ချင်း ပြန်ပေးပြီး try block ကနေ ထွက်သွားပါတယ်။ နောက်မှ ဖြစ်တဲ့ rejection ကို catch က မမြင်ပါဘူး။ try ထဲမှာဆိုရင် return await ... လို့ ရေးပါ။
Object method ကို arrow function နဲ့ ရေးတာ
Arrow function မှာ ကိုယ်ပိုင် this မရှိပါဘူး။ this ကို သုံးမယ့် method ဆိုရင် increment() { this.count++; } လို method syntax ကို သုံးပါ၊ ဒါမှမဟုတ် ဒီ lesson လို closure variable ကို သုံးပြီး this ကို လုံးဝ ရှောင်ပါ။
Memoize cache ကို function ထဲမှာ ကြေညာတာ
const cache = new Map() ကို return လုပ်တဲ့ function ထဲမှာ ရေးရင် call တိုင်း cache အသစ် ဆောက်လို့ ဘာမှ မမှတ်မိတော့ပါဘူး။ Cache က call တွေကြား ကျန်နေရမှာမို့ closure ရဲ့ အပြင်ဘက် (memoize ထဲ) မှာ ထားရပါမယ်။
Sync နဲ့ async output အစီအစဉ်ကို မှားခန့်မှန်းတာ
setTimeout(..., 0) ဆိုရင်တောင် callback က လက်ရှိ synchronous code အားလုံး ပြီးမှ run ပါတယ်။ Output အစီအစဉ်ကို ခန့်မှန်းတဲ့အခါ code ရေးထားတဲ့ အစီအစဉ်ကို မကြည့်ဘဲ sync နဲ့ async ကို ခွဲကြည့်ပါ။
Mini challenge
Concept နှစ်ခု ပေါင်း challenge သုံးခု
Challenge A: memoize(fn) ကို closure နဲ့ ရေးပြီး arg တစ်ခုအတွက် fn ကို တစ်ခါပဲ ခေါ်ပါ။ Challenge B: retry(task, attempts) ကို async loop နဲ့ ရေးပြီး task ပျက်ရင် attempts အကြိမ်အထိ ပြန်ကြိုးစားပါ။ Challenge C: private #items field၊ rest destructuring နဲ့ total getter ပါတဲ့ Inventory class ကို ရေးပါ။
- fastSquare(9) ကို နှစ်ခါ ခေါ်ရင် square ကို တစ်ခါပဲ တကယ် ခေါ်ရပါမယ်
- retry() က attempt တစ်ခုစီရဲ့ failure ကို log လုပ်ပြီး ကြိုးစားမှု ကုန်ရင် error ကို throw လုပ်ရပါမယ်
- Inventory ရဲ့ add() က this ကို return ပြန်လို့ chain လုပ်နိုင်ရပါမယ်
- #items ကို Object.keys(shop) မှာ မမြင်ရပါစေနဲ့
// Challenge A: closure + higher-order function
function memoize(fn) {
// TODO: keep a Map in the closure; return a function (arg) => result
// that calls fn(arg) only the first time it sees arg
}
// Challenge B: async/await + loop + try/catch
async function retry(task, attempts) {
// TODO: for i = 1..attempts, try `return await task(i)`;
// on failure log "attempt i failed: ..." and remember the error
// TODO: after the loop, throw "gave up after N attempts (last message)"
}
// Challenge C: private field + destructuring with rest + getter
class Inventory {
// TODO: a private #items array
add({ name, price, ...details }) {
// TODO: store the item, then return this so calls can be chained
}
get total() {
// TODO: sum every price with reduce
}
namesUnder(limit) {
// TODO: filter by price, then map to names
}
}
// TODO: test memoize with a function that counts its real calls,
// retry with a task that fails twice, and a three-item Inventoryရလဒ်: "81 81 16 real calls: 2"၊ attempt ပျက်တဲ့ log နှစ်ကြောင်းနောက်မှာ "result: data"၊ နောက်တစ်ခါ ပျက်တဲ့ log နှစ်ကြောင်းနဲ့ "final: gave up after 2 attempts (timeout)"၊ ပြီးရင် "total: 16300 | under 1000: ["Pen","Book"]" နဲ့ "private items visible? no" ထွက်ရပါမယ်။
အရိပ်အမြွက် ကြည့်ရန်
memoize မှာ cache.has(arg) နဲ့ စစ်ပါ (cache.get(arg) ရဲ့ truthy ကို မစစ်ပါနဲ့၊ ရလဒ် 0 ဖြစ်နိုင်လို့)။ retry မှာ loop ထဲက return await task(i) က အောင်တာနဲ့ function တစ်ခုလုံးကနေ ထွက်ပါတယ်။ Inventory ရဲ့ add() မှာ { name, price, ...details } က ကျန်တဲ့ field တွေကို details object ထဲ စုပေးပါတယ်။
အဖြေ ကြည့်ရန်
// Challenge A: closure + higher-order function
function memoize(fn) {
const cache = new Map();
return (arg) => {
if (!cache.has(arg)) cache.set(arg, fn(arg));
return cache.get(arg);
};
}
let slowCalls = 0;
const square = (n) => {
slowCalls++;
return n * n;
};
const fastSquare = memoize(square);
console.log(fastSquare(9), fastSquare(9), fastSquare(4), "real calls:", slowCalls);
// Challenge B: async/await + loop + try/catch
async function retry(task, attempts) {
let lastError;
for (let i = 1; i <= attempts; i++) {
try {
return await task(i); // the await matters: a rejection is caught here
} catch (err) {
lastError = err;
console.log(` attempt ${i} failed: ${err.message}`);
}
}
throw new Error(`gave up after ${attempts} attempts (${lastError.message})`);
}
const flaky = (attempt) =>
new Promise((resolve, reject) =>
setTimeout(() => (attempt < 3 ? reject(new Error("timeout")) : resolve("data")), 10));
console.log("result:", await retry(flaky, 3));
try {
await retry(flaky, 2);
} catch (err) {
console.log("final:", err.message);
}
// Challenge C: class with a private field, destructuring with rest, a getter
class Inventory {
#items = [];
add({ name, price, ...details }) {
this.#items.push({ name, price, details });
return this; // allows chaining
}
get total() {
return this.#items.reduce((sum, { price }) => sum + price, 0);
}
namesUnder(limit) {
return this.#items.filter(({ price }) => price < limit).map(({ name }) => name);
}
}
const shop = new Inventory()
.add({ name: "Pen", price: 500, color: "blue" })
.add({ name: "Bag", price: 15000 })
.add({ name: "Book", price: 800, pages: 120 });
console.log("total:", shop.total, "| under 1000:", JSON.stringify(shop.namesUnder(1000)));
console.log("private items visible?", Object.keys(shop).length === 0 ? "no" : "yes");Quick Quiz 1 / 3
Quick Quiz 2 / 3
Quick Quiz 3 / 3
မှတ်ထားရမယ့် အချက်များ
- Closure variable က object property ထက် ပိုလုံခြုံတဲ့ private state ပါ
- Instance တစ်ခုနဲ့ မဆိုင်တဲ့ logic (နှိုင်းယှဉ်တာ၊ factory) ကို static method အဖြစ် ထားပါ
- try/catch က rejection ကို ဖမ်းဖို့ await ကို try ထဲမှာ ရေးပါ
- Object method မှာ this လိုရင် arrow function မသုံးပါနဲ့
- Code မရေးခင် state ပိုင်ရှင်၊ sync/async၊ error လမ်းကြောင်း၊ this ကို စဉ်းစားပါ
MDN — JavaScript Guide — MDN Web Docs