मान लीजिए हमें एक सरणी फ़ंक्शन लिखना है, मान लीजिए prependN() जो एक संख्या n लेता है (n <= फ़ंक्शन के साथ उपयोग की जाने वाली सरणी की लंबाई) और यह अंत से n तत्व लेता है और उन्हें सरणी के सामने रखता है।
हमें इसे स्थानांतरित करके करना है और फ़ंक्शन को केवल कार्य के सफल समापन या विफलता के आधार पर बूलियन लौटाना चाहिए।
उदाहरण के लिए:
// यदि इनपुट सरणी है: const arr = ["blue", "red", "green", "orange", "yellow", "magenta", "cyan"]; // और संख्या n 3 है, // तो सरणी को इस तरह पुनर्व्यवस्थित किया जाना चाहिए: const output = ["yellow", "magenta", "cyan", "blue", "red", "green", "orange"]; // और फ़ंक्शन का वापसी मान 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' ]