ধরা যাক, আমাদের একটি অ্যারে ফাংশন লিখতে হবে, বলুন prependN() যেটি একটি সংখ্যা নেয় n (n <=ফাংশনের সাথে ব্যবহৃত অ্যারের দৈর্ঘ্য) এবং এটি শেষ থেকে n উপাদান নেয় এবং অ্যারের সামনে রাখে।
আমাদের এটি ঠিক জায়গায় করতে হবে এবং কার্যটির সফল সমাপ্তি বা ব্যর্থতার উপর ভিত্তি করে ফাংশনটি শুধুমাত্র একটি বুলিয়ান প্রদান করবে৷
যেমন −
// if the input array is: const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; // and the number n is 3, // then the array should be reshuffled like: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // and the return value of function should be true
এখন, এই ফাংশনের জন্য কোড লিখি -
উদাহরণ
const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; Array.prototype.reshuffle = function(num){ const { length: len } = this; if(num > len){ return false; }; const deleted = this.splice(len - num, num); this.unshift(...deleted); return true; }; console.log(arr.reshuffle(4)); console.log(arr);
আউটপুট
কনসোলে আউটপুট হবে −
true [ 'orange', 'yellow', 'magenta', 'cyan', 'blue', 'red', 'green' ]