ใช้ Math.random() ร่วมกับ map() และ Set เพื่อสุ่มดัชนีที่ไม่ซ้ำกัน
ตัวอย่างโค้ด
function substituteRandomValue(names, size) {
return function () {
const index = new Set();
do {
index.add(Math.floor(Math.random() * names.length));
} while (index.size < size);
return names.map((value, counter) => index.has(counter) ? 'Adam' : value);
};
}
var names = ['John', 'David', 'Bob', 'Mike', 'Carol', 'Sam'],
result = substituteRandomValue(names, 2);
console.log(...result());รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo278.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo278.js John David Bob Adam Carol Adam
คำอธิบาย: Closure คืนฟังก์ชันที่เมื่อเรียกจะสุ่มดัชนี size ตัว (ใช้ Set กันซ้ำ) แล้ว map สร้างอาร์เรย์ใหม่ แทนที่ดัชนีที่สุ่มได้ด้วย 'Adam'