Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การแปลงตัวเลขและตัวดำเนินการเป็นคำอ่านใน JavaScript


ปัญหา

เราต้องเขียนฟังก์ชัน JavaScript ที่รับสตริงของการดำเนินการทางคณิตศาสตร์ และคืนค่าคำอ่านตามตัวอักษร (literal wording)

ตัวอย่าง

โค้ดตัวอย่างดังนี้:

const str = '5 - 8';
const convertToWords = (str = '') => {
  const o = {
    "+" : "Plus",
    "-" : "Minus",
    "*" : "Times",
    "/" : "Divided By",
    "**" : "To The Power Of",
    "=" : "Equals",
    "!=" : "Does Not Equal",
  }
  const n = {
    1 : "One",
    2 : "Two",
    3 : "Three",
    4 : "Four",
    5 : "Five",
    6 : "Six",
    7 : "Seven",
    8 : "Eight",
    9 : "Nine",
    10 : "Ten",
  }
  let t = str.split(' ')
  let y = ''
  let c = 0
  for (const [key, value] of Object.entries(o)) {
    if(key !== t[1])
      c++;
  }
  if(c === Object.keys(o).length) return "That's not an operator!"
  for (const [key, value] of Object.entries(n)) {
    if(key === t[0])
      y += `${value} `
  }
  for (const [key, value] of Object.entries(o)) {
    if(key === t[1])
      y += `${value}`
  }
  for (const [key, value] of Object.entries(n)) {
    if(key === t[2])
      y += ` ${value}`
  }
  return y;
}
console.log(convertToWords(str));

ผลลัพธ์

Five Minus Eight