重构(第二版) 读书笔记 第一章 续

系列文章目录

重构(第二版) 读书笔记 第一章(从一个小程序入手,开始我们的第一次重构)



前言

上一篇文章我们对一段程序进行了基础的重构,并完成了以html格式打印详单的需求。这次我们来完成第二个需求:演员尝试更多的戏剧类型,对于新增的戏剧类型有新的计分方式。
上一篇代码最后的状态如下:

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;
    
    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: ${
     data.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 totalAmount(data) {
   
        return data.performances
            .reduce((total, p) => total + p.amount, 0);
    }
    function totalVolumeCredits(data) {
   
        return data.performances
            .reduce((total, p) => total + p.volumeCredits, 0);
    }
}
statement.js
import createStatementData from "./createStatementData.js";
const playsData = {
   
    "hamlet": {
    "name": "Hamlet", "type": "tragedy" },
    "as-like": {
    "name": "As You Like It", "type": "comedy" },
    "othello": {
    "name": "Othello", "type": "tragedy" }
}
const invoicesData = {
   
    "customer": "BigCo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值