हमें एक सरणी फ़ंक्शन (Array.prototype.get ()) लिखना है जो पहले तीन तर्क लेता है, एक संख्या n, दूसरा भी एक संख्या है, मान लीजिए एम, (एम <=सरणी लंबाई -1) और दूसरा एक स्ट्रिंग है जिसमें दो में से एक मान हो सकता है - 'बाएं' या 'दाएं'।
फ़ंक्शन को मूल सरणी का एक उप-सरणी वापस करना चाहिए जिसमें n तत्व शामिल होने चाहिए जो सूचकांक m से शुरू होते हैं, और निर्दिष्ट दिशा में जैसे बाएं या दाएं।
उदाहरण के लिए -
// if the array is: const arr = [0, 1, 2, 3, 4, 5, 6, 7]; // and the function call is: arr.get(4, 6, 'right'); // then the output should be: const output = [6, 7, 0, 1];
तो, चलिए इस फ़ंक्शन के लिए कोड लिखते हैं -
उदाहरण
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
Array.prototype.get = function(num, ind, direction){
const amount = direction === 'left' ? -1 : 1;
if(ind > this.length-1){
return false;
};
const res = [];
for(let i = ind, j = 0; j < num; i += amount, j++){
if(i > this.length-1){
i = i % this.length;
};
if(i < 0){
i = this.length-1;
};
res.push(this[i]);
};
return res;
};
console.log(arr.get(4, 6, 'right'));
console.log(arr.get(9, 6, 'left')); आउटपुट
कंसोल में आउटपुट होगा -
[ 6, 7, 0, 1 ] [ 6, 5, 4, 3, 2, 1, 0, 7, 6 ]