เราต้องเขียนฟังก์ชันอาร์เรย์ (Array.prototype.get()) ที่รับสามอาร์กิวเมนต์ ตัวแรก ตัวเลข n ตัวที่สองก็เป็นตัวเลข m (m <= ความยาวอาร์เรย์ - 1) และตัวที่สามเป็นสตริงที่มีค่าได้สองอย่างคือ 'left' หรือ 'right'
ฟังก์ชันควรคืนค่าซับอาร์เรย์ของอาร์เรย์ต้นฉบับที่มี n องค์ประกอบเริ่มจากดัชนี m และในทิศทางที่ระบุ เช่น left หรือ right
ตัวอย่างเช่น:
// หากอาร์เรย์คือ: 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]