讓我們來看一個(gè)遵循命令式模型的“ calculatePrice”函數(shù)的實(shí)現(xiàn):
const calculatePrice = (price, tax, discount) => {const priceWithTaxes = withTaxes(tax, price);if (isError(priceWithTaxes)) {return console.log('Error: ' + priceWithTaxes.message);}const priceWithTaxesAndDiscount = withDiscount(discount, priceWithTaxes);if (isError(priceWithTaxesAndDiscount)) {return console.log('Error: ' + priceWithTaxesAndDiscount.message);}console.log('Total Price: ' + priceWithTaxesAndDiscount);}//我們計(jì)算出價(jià)值25的產(chǎn)品(含21%的增值稅和10%的折扣)的最終價(jià)格 。calculatePrice(25, 0.21, 0.10)現(xiàn)在,讓我們了解如何使用Either Monad重寫此函數(shù) 。
都有兩個(gè)構(gòu)造函數(shù),Left和Right 。我們要實(shí)現(xiàn)的是將異常存儲(chǔ)到Left構(gòu)造函數(shù),并將正常結(jié)果(快樂路徑)存儲(chǔ)到Right構(gòu)造函數(shù) 。
首先,將更改已經(jīng)存在的withTaxes和withDiscount函數(shù),以便在出現(xiàn)錯(cuò)誤時(shí)它們返回Left,在一切正常的情況下返回Right:
const withTaxes = Ramda.curry((tax, price) => {if (!_.isNumber(price)) {return RamdaFantasy.Either.Left(new Error("Price is not numeric"));}return RamdaFantasy.Either.Right(price + (tax * price)); });const withDiscount = Ramda.curry((dis, price) => {if (!_.isNumber(price)) {return RamdaFantasy.Either.Left(new Error("Price is not numeric"));}if (price < 5) {return RamdaFantasy.Either.Left(new Error("Discounts not available for low-priced items"));}return RamdaFantasy.Either.Right(price - (price * dis)); });
然后,我們?yōu)镽ight案例創(chuàng)建一個(gè)函數(shù)(顯示價(jià)格),為Left案例創(chuàng)建另一個(gè)函數(shù)(顯示錯(cuò)誤),然后使用它們創(chuàng)建Either Monad:
const showPrice = (total) => { console.log('Price: ' + total) }; const showError = (error) => { console.log('Error: ' + error.message); }; const eitherErrorOrPrice = RamdaFantasy.Either.either(showError, showPrice);最后,只需要執(zhí)行Monad來計(jì)算最終價(jià)格:
//計(jì)算出價(jià)值25的產(chǎn)品(含21%的增值稅和10%的折扣)的最終價(jià)格 。eitherErrorOrPrice(RamdaFantasy.Either.Right(25).chain(withTaxes(0.21)).chain(withDiscount(0.1)))結(jié)論:JavaScript中的函數(shù)式編程正如我們所看到的,一旦用Maybe和Either單子分解了代碼,就沒有那么復(fù)雜了 。如果使用得當(dāng),它們可以使我們的代碼更易于閱讀和維護(hù) 。
【foreach跳出本次循環(huán) js判斷空對象的方法】唯一的不便是我們需要克服的初始障礙,但這可以通過在網(wǎng)上一些示例并進(jìn)行一些測試來完成 。
推薦閱讀
- 本次題目蒸花卷時(shí)怎樣讓蔥花翠綠而不變黃
- 伊蘇8跳出解決辦法分享 伊蘇8游戲一直跳出怎么辦
- 《孤島驚魂:原始?xì)⒙尽酚螒蚶鲜翘鲚斎敕▎栴}解決方法解析攻略
- 孤島驚魂原始?xì)⒙酒平獍嫜┑靥鲈趺唇鉀Q?
- 天命奇御2黑屏卡死怎么辦 跳出黑屏打不開問題解決方法匯總
- 《孤島驚魂3》解決黑屏和崩潰跳出方法
- 2022宜興事業(yè)單位考試地點(diǎn)
- 《群星》軍事基地跳出解決方法
- 《群星》造要塞跳出解決心得分享
- 哪套外觀在5天的投票角逐中勝出成為本次第三期戰(zhàn)令解鎖外觀 天涯明月刀手游3月11日每日一題答案
