हमें एक सरणी फ़ंक्शन (Array.prototype.get()) लिखना है जो तीन तर्क लेता है: पहला, एक संख्या n, दूसरी भी एक संख्या, मान लीजिए m, (m <= सरणी लंबाई-1) और तीसरा एक स्ट्रिंग जो दो मानों में से एक हो सकती है - 'left' या 'right'।
फ़ंक्शन को मूल सरणी की एक उप-सरणी लौटानी चाहिए जिसमें n तत्व हों जो सूचकांक m से शुरू हों, और निर्दिष्ट दिशा में जैसे बाएँ या दाएँ।
उदाहरण के लिए:
// यदि सरणी है: const arr = [0, 1, 2, 3, 4, 5, 6, 7]; // और फ़ंक्शन कॉल है: arr.get(4, 6, 'right'); // तो आउटपुट होना चाहिए: 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]