ภาพรวม
บทความนี้สาธิตวิธีเขียนฟังก์ชันที่รับสตริงและตัวเลข n แล้วคืนสตริงใหม่ที่ตัวอักษรแต่ละตัวถูกทำซ้ำ n ครั้ง
ตัวอย่าง
Input: 'how are you', n = 2
Output: 'hhooww aarree yyoouu'
การนำไปใช้
const repeatNTimes = (str, n) => {
let res = '';
for (let i = 0; i < str.length; i++) {
res += str[i].repeat(n);
}
return res;
};
console.log(repeatNTimes('how are you', 2));
ผลลัพธ์
hhooww aarree yyoouu
วิธีการทันสมัย (ES6+)
// ใช้ spread operator และ map
const repeatNTimesModern = (str, n) =>
[...str].map(c => c.repeat(n)).join('');
// ใช้ replace กับ regex
const repeatNTimesRegex = (str, n) =>
str.replace(/./gs, c => c.repeat(n));
// ใช้ reduce
const repeatNTimesReduce = (str, n) =>
[...str].reduce((acc, c) => acc + c.repeat(n), '');
การจัดการ Unicode (Emoji, Thai Characters)
// ใช้ [...str] แทน str.split('') เพื่อรองรับ Surrogate Pairs
const repeatNTimesUnicode = (str, n) =>
Array.from(str).map(c => c.repeat(n)).join('');
// ทดสอบ
console.log(repeatNTimesUnicode('😀🎉', 2)); // 😀😀🎉🎉
console.log(repeatNTimesUnicode('สวัสดี', 2)); // สสววััสสดดีี
การประยุกต์ใช้
- Text Effects / Visual Effects
- Stuttering Effect ใน Game Dialogue
- Data Augmentation สำหรับ NLP
- CAPTCHA Generation
ข้อควรระวัง
- String.prototype.repeat() รองรับใน ES2016+
- n ติดลบหรือ 0 จะคืน Empty String
- n ไม่ใช่ Integer จะถูกแปลง (Math.floor)
- สตริงยาวมาก + n ใหญ่ อาจทำให้ Memory หมด