ปัญหา
เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงและเข้ารหัสโดยใช้อัลกอริธึมต่อไปนี้ -
-
สตริงประกอบด้วยคำที่คั่นด้วยช่องว่างเท่านั้น
-
เราจำเป็นต้องเข้ารหัสแต่ละคำในสตริงโดยใช้กฎต่อไปนี้:
-
ต้องแปลงอักษรตัวแรกเป็นรหัส ASCII
-
ต้องเปลี่ยนตัวอักษรตัวที่สองด้วยตัวอักษรตัวสุดท้าย
-
ดังนั้น ตามนี้ สตริง 'ดี' จะถูกเข้ารหัสเป็น '103doo'
ตัวอย่าง
ต่อไปนี้เป็นรหัส -
const str = 'good';
const encyptString = (str = '') => {
const [first, second] = str.split('');
const last = str[str.length - 1];
let res = '';
res += first.charCodeAt(0);
res += last;
for(let i = 2; i < str.length - 1; i++){
const el = str[i];
res += el;
};
res += second;
return res;
};
console.log(encyptString(str)); ผลลัพธ์
103doo