Try   HackMD

Combine Function into Transform

練習用的 REPL

// 這是 reading 的資料結構 reading = {customer: "ivan", quantity: 10, month: 5, year: 2017}; // 三個呼叫端都要計算 baseCharge,但命名不見得一樣,甚至計算方法也在各地重複了 // client 1 const aReading = acquireReading(); const baseCharge = baseRate(aReading.month, aReading.year) * aReading.quantity; // client 2 const aReading = acquireReading(); const base = (baseRate(aReading.month, aReading.year) * aReading.quantity); const taxableCharge = Math.max(0, base - taxThreshold(aReading.year)); // client 3 const aReading = acquireReading(); const basicChargeAmount = calculateBaseCharge(aReading); function calculateBaseCharge(aReading) { return baseRate(aReading.month, aReading.year) * aReading.quantity; }

先做個 transform function,單純回傳複製後的物件。

function enrichReading(original) { const result = _.cloneDeep(original); return result; } // client 3 比較單純,先套用 // client 3 const rawReading = acquireReading(); // 名字改一下 const aReading = enrichReading(rawReading); // 先用上 transform function const basicChargeAmount = calculateBaseCharge(aReading);

然後把 calculateBaseCharge 移入 transform function。

function enrichReading(original) { const result = _.cloneDeep(original); result.baseCharge = calculateBaseCharge(result); return result; } // client 3 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const basicChargeAmount = aReading.baseCharge; // 這邊就可以換成取值 // client 1 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); // 這邊就可以換成取值 const baseCharge = aReading.baseCharge;
// client 2 毛比較多 // 先套用 transform function const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const base = (baseRate(aReading.month, aReading.year) * aReading.quantity); const taxableCharge = Math.max(0, base - taxThreshold(aReading.year)); // baseCharge 改成取值 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const base = aReading.baseCharge; // 這邊就可以換成取值 const taxableCharge = Math.max(0, base - taxThreshold(aReading.year)); // 其他地方也改成取值 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const taxableCharge = Math.max(0, aReading.baseCharge - taxThreshold(aReading.year)); // 這邊就可以換成取值

繼續把 taxableCharge 移入 transform function。

function enrichReading(original) { const result = _.cloneDeep(original); result.baseCharge = calculateBaseCharge(result); result.taxableCharge = Math.max(0, result.baseCharge - taxThreshold(result.year)); // 把 taxableCharge 也納進來 return result; } // 這是剛剛的 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const taxableCharge = Math.max(0, aReading.baseCharge - taxThreshold(aReading.year)); // 可以再變成這樣 const rawReading = acquireReading(); const aReading = enrichReading(rawReading); const taxableCharge = aReading.taxableCharge; // 這邊就可以換成取值