একটি স্ট্রিং থেকে সবচেয়ে ছোট এবং বড় শব্দ বের করে অ্যারে আকারে রিটার্ন করা।
উদাহরণ
"Hardships often prepare ordinary people for an extraordinary destiny" // ছোট: "an" (২ অক্ষর) // বড়: "extraordinary" (১২ অক্ষর)
সমাধান
const largestSmallest = (str) => {
// স্পেস দিয়ে স্প্লিট (একাধিক স্পেস হ্যান্ডল করতে regex)
const words = str.trim().split(/\s+/);
if (words.length === 0) return ['', ''];
let min = words[0];
let max = words[0];
for (let i = 1; i < words.length; i++) {
if (words[i].length < min.length) {
min = words[i];
}
if (words[i].length > max.length) {
max = words[i];
}
}
return [min, max];
};
// ফাংশনাল পদ্ধতি
const largestSmallestFP = (str) => {
const words = str.trim().split(/\s+/);
if (!words.length) return ['', ''];
const min = words.reduce((a, b) => a.length <= b.length ? a : b);
const max = words.reduce((a, b) => a.length >= b.length ? a : b);
return [min, max];
};
// টেস্ট
const str = "Hardships often prepare ordinary people for an extraordinary destiny";
console.log(largestSmallest(str)); // ['an', 'extraordinary']
console.log(largestSmallestFP(str)); // ['an', 'extraordinary']
এজ কেস হ্যান্ডলিং
const robustLargestSmallest = (str) => {
if (!str || typeof str !== 'string') return ['', ''];
const words = str.trim().split(/\s+/).filter(w => w.length > 0);
if (!words.length) return ['', ''];
return words.reduce(
([min, max], word) => [
word.length < min.length ? word : min,
word.length > max.length ? word : max
],
[words[0], words[0]]
);
};
উৎপাদন
[ 'an', 'extraordinary' ]