日本免费全黄少妇一区二区三区-高清无码一区二区三区四区-欧美中文字幕日韩在线观看-国产福利诱惑在线网站-国产中文字幕一区在线-亚洲欧美精品日韩一区-久久国产精品国产精品国产-国产精久久久久久一区二区三区-欧美亚洲国产精品久久久久

foreach跳出本次循環(huán) js判斷空對象的方法( 二 )

讓我們來看一個(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)行一些測試來完成 。

推薦閱讀