ฟังก์ชันนี้แปลงสตริงตัวพิมพ์เล็กเป็นสตริงไบนารี โดย:
- a-m → 0
- n-z → 1
- สัญลักษณ์อื่น (ช่องว่าง, หมายเลข, ปunctuation) → คงเดิม
ตัวอย่าง
// Input: 'Hello worlld how are you' // Output: '00001 111000 011 010 111'
ตัวอย่างโค้ด
const str = 'Hello worlld how are you';
const stringToBinary = (str = '') => {
const s = str.toLowerCase();
let res = '';
for (let i = 0; i < s.length; i++) {
// ตรวจสอบว่าตัวอักษรหรือไม่ (ตัวพิมพ์ใหญ่/เล็กเท่ากัน = ไม่ใช่ตัวอักษร)
if (s[i].toLowerCase() === s[i].toUpperCase()) {
res += s[i];
continue;
}
// a-m = 0, n-z = 1
res += s[i] > 'm' ? '1' : '0';
}
return res;
};
console.log(stringToBinary(str));
การทำงาน
- แปลงเป็นตัวพิมพ์เล็กทั้งหมด
- ตรวจสอบตัวอักษร:
toLowerCase() === toUpperCase()→ ไม่ใช่ตัวอักษร - เปรียบเทียบกับ 'm': มากกว่า = 1, น้อยกว่าหรือเท่ากัน = 0
ผลลัพธ์
00001 111000 011 010 111
ประยุกต์ใช้: การเข้ารหัสง่ายๆ การบีบอัดข้อมูล การสร้างฟีเจอร์สำหรับ ML