โจทย์
เขียนฟังก์ชัน rotate array โดยเลื่อน n elements
Input: const arr = [12, 6, 43, 5, 7, 2, 5], n=3
Output: [5, 7, 2, 5, 12, 6, 43]
ตัวอย่างโค้ด
// rotation
const arr = [12, 6, 43, 5, 7, 2, 5];
const rotateByOne = arr => {
for(let i = 0; i < arr.length-1; i++){
temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
};
};
Array.prototype.rotateBy = function(n){
const { length: l } = this;
if(n >= l){ return; };
for(let i = 0; i < n; i++){
rotateByOne(this);
};
};
const a = [1,2,3,4,5,6,7];
a.rotateBy(2);
console.log(a);
ผลลัพธ์
[ 3, 4, 5, 6, 7, 1, 2 ]
คำอธิบาย
rotateByOne เลื่อก elements ซ้าย 1 ตำแหน่ง (swap adjacent)Array.prototype.rotateBy extend prototype เรียก rotateByOne n ครั้ง
ตัวอย่าง a=[1,2,3,4,5,6,7] rotateBy(2) → [3,4,5,6,7,1,2]
หมายเหตุ: การ extend built-in prototype ไม่แนะนำใน production code