let plays = {
"hamlet": {"name": "Hamlet", "type": "tragedy"},
"as-like": {"name": "As You Like It", "type": "comedy"},
"othello": {"name": "Othello", "type": "tragedy"}
};
let invoice = {
customer: "BigCo",
performances: [
{
playID: "hamlet",
audience: 55
},
{
playID: "as-like",
audience: 35
},
{
playID: "othello",
audience: 40
}
]
};
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`;
console.log(result)
return result;
}
statement(invoice, plays)
開始
- 提煉函數,刪除thisAmount變量 thisAmount–>function amountFor(perf,play)
- 修改函數內部變量名
- thisAmount–>result
- perf -->aPerformance(a代表類型)
提煉函數,刪除play變量 play–>function playFor(aPerformance)
- 提煉函數,volumeCredits–>function volumeCreditsFor(perf)
- 提煉函數,刪除format變量 format–>function usd(aNumber)
移除volumeCredits變量
4. 拆分循環
5. 移動語句
6. 提煉函數
7. 移除內聯變量
同樣的過程,刪除totalAmount,result
目前代碼
添加一個數據結構 statementData,將customer,performances添加到此數據結構中。這樣可以移除renderPlainText函數的invoice變量。
劇目名稱也存在statementData數據對象中。
替換renderPlainText中所有playFor的引用
同樣的方法,將amount,volumeCredits提取出來。
並將兩個求總和的函數提取到statement函數中。
以管道取代循環
將數據和打印函數分離,將打印函數提取到外層。
拆分代碼爲兩個文件
statement.js
import createStatementData from "./createStatementData";
let plays = {
"hamlet": { "name": "Hamlet", "type": "tragedy" },
"as-like": { "name": "As You Like It", "type": "comedy" },
"othello": { "name": "Othello", "type": "tragedy" }
};
let invoice =
{
customer: "BigCo",
performances: [
{
playID: "hamlet",
audience: 55
},
{
playID: "as-like",
audience: 35
},
{
playID: "othello",
audience: 40
}
]
};
function statement(invoice,plays){
return renderPlainText(createStatementData(invoice,plays));
}
//打印訂單
function renderPlainText(data) {
let result = `Statement for ${data.customer}\n`;
for (let perf of data.performances) {
result += ` ${perf.play.name}: ${usd(perf.amount)} (${perf.audience} seats)\n`;
}
result += `Amount owed is ${usd(data.totalAmount)}\n`;
result += `You earned ${data.totalVolumeCredits} credits\n`;
console.log('text\n',result)
return result;
}
function htmlStatement (invoice, plays) {
return renderHtml(createStatementData(invoice, plays));
}
function renderHtml (data) {
let result = `<h1>Statement for ${data.customer}</h1>\n`;
result += "<table>\n";
result += "<tr><th>play</th><th>seats</th><th>cost</th></tr>";
for (let perf of data.performances) {
result += ` <tr><td>${perf.play.name}</td><td>${perf.audience}</td>`;
result += `<td>${usd(perf.amount)}</td></tr>\n`;
}
result += "</table>\n";
result += `<p>Amount owed is <em>${usd(data.totalAmount)}</em></p>\n`;
result += `<p>You earned <em>${data.totalVolumeCredits}</em> credits</p>\n`;
console.log('html\n',result)
return result;
}
//格式化數字貨幣
function usd(aNumber) {
return new Intl.NumberFormat("en-US",
{
style: "currency", currency: "USD",
minimumFractionDigits: 2
}).format(aNumber / 100);
}
statement(invoice, plays)
htmlStatement(invoice, plays)
createStatementData.js
export default function createStatementData(invoice, plays) {
const statementData = {};
statementData.customer = invoice.customer;
statementData.performances = invoice.performances.map(enrichPerformance);
statementData.totalAmount = totalAmount(statementData);
statementData.totalVolumeCredits = totalVolumeCredits(statementData)
return statementData;
//performances對象副本
function enrichPerformance(aPerformance) {
const result = Object.assign({}, aPerformance);
result.play = playFor(result);
result.amount = amountFor(result);
result.volumeCredits = volumeCreditsFor(result);
return result;
}
//劇目名稱
function playFor(aPerformance) {
return plays[aPerformance.playID];
}
//計算演出費用
function amountFor(aPerformance) {
let result = 0;
switch (aPerformance.play.type) {
case "tragedy":
result = 40000;
if (aPerformance.audience > 30) {
result += 1000 * (aPerformance.audience - 30);
}
break;
case "comedy":
result = 30000;
if (aPerformance.audience > 20) {
result += 10000 + 500 * (aPerformance.audience - 20);
}
result += 300 * aPerformance.audience;
break;
default:
throw new Error(`unknown type: ${aPerformance.play.type}`);
}
return result;
}
//觀衆量積分
function volumeCreditsFor(aPerformance) {
let result = 0;
result += Math.max(aPerformance.audience - 30.0);
if ("comedy" === aPerformance.play.type) result += Math.floor(aPerformance.audience / 5);
return result;
}
//觀衆量積分總和
function totalVolumeCredits(data) {
return data.performances.reduce((total, p) => total + p.volumeCredits, 0);
}
// 總賬單
function totalAmount(data) {
return data.performances.reduce((total, p) => total + p.amount, 0);
}
}
純js文件無法使用export、import,所以使用了打包工具webpack,也可以使用其他。(也可以直接使用require)
//package.json
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "webpack",
"start": "webpack-dev-server --open"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"clean-webpack-plugin": "^2.0.2",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.31.0",
"webpack-cli": "^3.3.2",
"webpack-dev-server": "^3.3.1"
},
"dependencies": {
"lodash": "^4.17.11"
}
}
//webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
statement: './src/statement.js'
},
devtool: 'inline-source-map',
devServer: {
contentBase: './dist'
},
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({ template: './index.html' })
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
npm install
安裝
npm run start
可在網頁的控制檯看到輸出
以下更改的爲createStatementData.js文件
按類型重組數據類型
將函數搬進演出計算器
將amountFor函數代碼,移到PerformanceCalculator演出計算器中,並修改參數(aPerformance ->this.performance,playFor(aPerformance)->this.play)
將amountFor改成委託函數
引用處修改
同樣的方法,將volumeCredits
將volumeCreditsFor函數代碼,移到PerformanceCalculator演出計算器中,並修改參數。
使演出計算器表現出多態性
工廠函數取代構造函數
創建子類
觀衆量積分
我注意到大多數戲劇都會檢查觀衆是否超過30,只有一些不同。因此,將更爲通用的邏輯放到超類作爲默認條件,出現在特殊場景時,覆蓋它。
statement.js未做修改,在上面有代碼。
createStatementData.js最終代碼
//演出計算器
class PerformanceCalculator {
constructor(aPerformance, aPlay) {
this.performance = aPerformance;
this.play = aPlay;
}
get amount() {
throw new Error('subclass responsibility子類任務');
}
get volumeCredits() {
return Math.max(this.performance.audience - 30.0);
}
}
class TragedyCalculator extends PerformanceCalculator {
get amount() {
let result = 40000;
if (this.performance.audience > 30) {
result += 1000 * (this.performance.audience - 30);
}
return result;
}
}
class ComedyCalculator extends PerformanceCalculator {
get amount() {
let result = 30000;
if (this.performance.audience > 20) {
result += 10000 + 500 * (this.performance.audience - 20);
}
result += 300 * this.performance.audience;
return result;
}
get volumeCredits() {
return super.volumeCredits + Math.floor(this.performance.audience / 5);
}
}
function createPerformanceCalculator(aPerformance, aPlay) {
switch(aPlay.type) {
case "tragedy": return new TragedyCalculator(aPerformance, aPlay);
case "comedy" : return new ComedyCalculator(aPerformance, aPlay);
default:
throw new Error(`unknown type: ${aPlay.type}`);
}
}
export default function createStatementData(invoice, plays) {
const statementData = {};
statementData.customer = invoice.customer;
statementData.performances = invoice.performances.map(enrichPerformance);
statementData.totalAmount = totalAmount(statementData);
statementData.totalVolumeCredits = totalVolumeCredits(statementData)
return statementData;
//performances對象副本
function enrichPerformance(aPerformance) {
const calculator = createPerformanceCalculator(aPerformance, playFor(aPerformance));
const result = Object.assign({}, aPerformance);
result.play = calculator.play;
result.amount = calculator.amount;
result.volumeCredits = calculator.volumeCredits;
return result;
}
//劇目名稱
function playFor(aPerformance) {
return plays[aPerformance.playID];
}
//觀衆量積分總和
function totalVolumeCredits(data) {
return data.performances.reduce((total, p) => total + p.volumeCredits, 0);
}
// 總賬單
function totalAmount(data) {
return data.performances.reduce((total, p) => total + p.amount, 0);
}
}
正常工作時invoice應該是數組
invoice.forEach(item => {
statement(item, plays)
htmlStatement(item, plays)
})