《重构 改善既有代码的设计》 马丁 富勒
第一章
戏剧演出团原始代码
invoices.json
[ { "customer": "BigCo", "performances": [ { "playId": "hamlet", "audience": 55 }, { "playId": "as-like", "audience": 35 }, { "playId": "othello", "audience": 40 } ] } ]
plays.json
{ "hamlet": {"name": "Hamlet", "type": "tragedy"}, "as-like": {"name": "As You Like It", "type": "comedy"}, "othello": {"name": "Othello", "type": "tragedy"} }
main.js
const invoices = require('./invoices.json') const plays = require('./plays.json') 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(`unknow 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; } console.log(statement(invoices[0], plays));
运行结果
------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- ------------------------- -------------------------
标签:重构,plays,第一个,示例,type,thisAmount,audience,-------------------------,perf From: https://www.cnblogs.com/ives-xu/p/17689105.html