The Starting Point (จุดเริ่มต้น)

ในฉบับพิมพ์ครั้งแรกของหนังสือเล่มนี้ โปรแกรมตั้งต้นของผมพิมพ์ใบแจ้งหนี้จากร้านเช่าวิดีโอ ซึ่งตอนนี้อาจทำให้หลายคนถามว่า “ร้านเช่าวิดีโอคืออะไร?” แทนที่จะตอบคำถามนั้น ผมขอปรับโฉมตัวอย่างให้เป็นอะไรที่ทั้งเก่ากว่าและยังคงร่วมสมัย

ลองนึกภาพบริษัทนักแสดงละครเวทีที่ออกไปแสดงตามงานอีเวนต์ต่าง ๆ โดยทั่วไปลูกค้าจะจอง performance สองสามชุด และบริษัทจะคิดเงินตามจำนวนผู้ชมและประเภทของ performance ที่พวกเขาแสดง ปัจจุบันบริษัทแสดงละครอยู่สองประเภทคือ โศกนาฏกรรม (tragedy) และตลก (comedy) นอกจากการออกใบแจ้งหนี้สำหรับ performance แล้ว บริษัทยังให้ “volume credits” กับลูกค้าซึ่งใช้เป็นส่วนลดใน performance ครั้งต่อไป—คิดซะว่าเป็นกลไกสะสมความภักดีของลูกค้า

นักแสดงเก็บข้อมูลการแสดงของพวกเขาไว้ในไฟล์ JSON ง่าย ๆ ที่มีหน้าตาประมาณนี้:

plays.json…

{
  "hamlet": {"name": "Hamlet", "type": "tragedy"},
  "as-like": {"name": "As You Like It", "type": "comedy"},
  "othello": {"name": "Othello", "type": "tragedy"}
}

ข้อมูลสำหรับการออกใบแจ้งหนี้ก็มาในไฟล์ JSON เช่นกัน:

invoices.json…

[
  {
    "customer": "BigCo",
    "performances": [
      {
        "playID": "hamlet",
        "audience": 55
      },
      {
        "playID": "as-like",
        "audience": 35
      },
      {
        "playID": "othello",
        "audience": 40
      }
    ]
  }
]

code ที่พิมพ์ใบแจ้งหนี้ออกมาเป็น function ง่าย ๆ function นี้:

function statement (invoice, plays) {
  let totalAmount = 0;
  let volumeCredits = 0;
  let result = `Statement for ${invoice.customer}\n`;
  const format = new Intl.NumberFormat("en-US",
                        { style: "currency", currency: "USD",
                          minimumFractionDigits: 2 }).format;
  for (let perf of invoice.performances) {
    const play = plays[perf.playID];
    let thisAmount = 0;

    switch (play.type) {
    case "tragedy":
      thisAmount = 40000;
      if (perf.audience > 30) {
        thisAmount += 1000 * (perf.audience - 30);
      }
      break;
    case "comedy":
      thisAmount = 30000;
      if (perf.audience > 20) {
        thisAmount += 10000 + 500 * (perf.audience - 20);
      }
      thisAmount += 300 * perf.audience;
      break;
    default:
        throw new Error(`unknown type: ${play.type}`);
    }

    // add volume credits
    volumeCredits += Math.max(perf.audience - 30, 0);
    // add extra credit for every ten comedy attendees
    if ("comedy" === play.type) volumeCredits += Math.floor(perf.audience / 5);

    // print line for this order
    result += `  ${play.name}: ${format(thisAmount/100)} (${perf.audience} seats)\n`;
    totalAmount += thisAmount;
  }
  result += `Amount owed is ${format(totalAmount/100)}\n`;
  result += `You earned ${volumeCredits} credits\n`;
  return result;
}

เมื่อรัน code นั้นกับไฟล์ข้อมูล test ด้านบน จะได้ผลลัพธ์ดังนี้:

Statement for BigCo
  Hamlet: $650.00 (55 seats)
  As You Like It: $580.00 (35 seats)
  Othello: $500.00 (40 seats)
Amount owed is $1,730.00
You earned 47 credits