ভূমিকা
নৌকা/বোট আপস্ট্রিম (ধারার বিপরীত) এবং ডাউনস্ট্রিম (ধারার অনুপাতিক) চলার সময় ভেলোসিটি ভিন্ন হয়। এই আর্টিকেলে অবজেক্টের অ্যারে থেকে নেট ভেলোসিটি (আপস্ট্রিম - ডাউনস্ট্রিম) বের করার ফাংশন দেখানো হয়েছে।
সম্পূর্ণ কোড
const arr = [
{ direction: 'upstream', velocity: 45 },
{ direction: 'downstream', velocity: 15 },
{ direction: 'downstream', velocity: 50 },
{ direction: 'upstream', velocity: 35 },
{ direction: 'downstream', velocity: 25 },
{ direction: 'upstream', velocity: 40 },
{ direction: 'upstream', velocity: 37.5 }
];
const findNetVelocity = (arr) => {
const netVelocity = arr.reduce((acc, val) => {
const { direction, velocity } = val;
if (direction === 'upstream') {
return acc + velocity;
} else {
return acc - velocity;
}
}, 0);
return netVelocity;
};
console.log(findNetVelocity(arr)); // 67.5
কোড ব্যাখ্যা
- reduce() - অ্যাকুমুলেটর (`acc`) ০ থেকে শুরু
- Destructuring: `{ direction, velocity } = val` - অবজেক্ট থেকে ভ্যালু এক্সট্র্যাক্ট
- শর্ত: `upstream` হলে যোগ, `downstream` হলে বিয়োগ
- ফলাফল: নেট ভেলোসিটি রিটার্ন
গণনা প্রক্রিয়া
| Direction | Velocity | Operation | Running Total |
|---|---|---|---|
| upstream | 45 | +45 | 45 |
| downstream | 15 | -15 | 30 |
| downstream | 50 | -50 | -20 |
| upstream | 35 | +35 | 15 |
| downstream | 25 | -25 | -10 |
| upstream | 40 | +40 | 30 |
| upstream | 37.5 | +37.5 | 67.5 |
আউটপুট
67.5
বিকল্প পদ্ধতিগুলো
১. Filter + Reduce (আরো পঠনযোগ্য)
const findNetVelocity = (arr) => {
const upstream = arr
.filter(d => d.direction === 'upstream')
.reduce((sum, d) => sum + d.velocity, 0);
const downstream = arr
.filter(d => d.direction === 'downstream')
.reduce((sum, d) => sum + d.velocity, 0);
return upstream - downstream;
};
২. For Loop (সর্বোচ্চ পারফরম্যান্স)
const findNetVelocity = (arr) => {
let net = 0;
for (const { direction, velocity } of arr) {
net += direction === 'upstream' ? velocity : -velocity;
}
return net;
};
৩. Map/Filter চেইন (ফাংশনাল)
const findNetVelocity = arr =>
arr.map(d => d.direction === 'upstream' ? d.velocity : -d.velocity)
.reduce((a, b) => a + b, 0);
বাস্তব অ্যাপ্লিকেশন
- নৌচালন: নদীতে বোটের কার্যকর গতি
- হাইড্রোলজি: নদীর প্রবাহ বিশ্লেষণ
- ফিজিক্স সিমুলেশন: সাপেক্ষ গতি গণনা
- গেম ডেভ: হোভারক্রাফট/বোট মিউভমেন্ট
সারাংশ
`reduce()` মেথড একটি পাসে (single pass) নেট ভেলোসিটি বের করার জন্য আদর্শ। ডিস্ট্রাকচারিং এবং টার্নারি অপারেটর কোডকে সংক্ষিপ্ত ও পঠনযোগ্য করে।