আমাদের একটি জাভাস্ক্রিপ্ট ফাংশন লিখতে হবে যা একটি স্ট্রিং এবং একটি সংখ্যা n নেয় (যেমন n ঠিক স্ট্রিংয়ের দৈর্ঘ্যকে ভাগ করে)। আমাদের স্ট্রিং এর n সমান অংশ সমন্বিত দৈর্ঘ্য n এর একটি অ্যারে ফেরত দিতে হবে।
চলুন এই ফাংশনের জন্য কোড লিখি -
উদাহরণ
const str = 'this is a sample string';
const num = 5;
const divideEqual = (str, num) => {
const len = str.length / num;
const creds = str.split("").reduce((acc, val) => {
let { res, currInd } = acc;
if(!res[currInd] || res[currInd].length < len){
res[currInd] = (res[currInd] || "") + val;
}else{
res[++currInd] = val;
};
return { res, currInd };
}, {
res: [],
currInd: 0
});
return creds.res;
};
console.log(divideEqual(str, num)); আউটপুট
নিম্নোক্ত কনসোলে আউটপুট −
[ 'this ', 'is a ', 'sampl', 'e str', 'ing' ]