函数组合与CoffeeScript编程风格
1. 函数组合基础
1.1 Compose组合函数
在实际编程中,我们经常会遇到需要将多个函数的操作依次执行的情况。例如,计算税款时,需要先计算所有产品的净利润,再根据净利润计算税款。
profit = ->
tax = (amount) ->
amount / 3
netProfit = (products) ->
profits = (profit product) for product in products
profits.reduce (acc, p) -> acc + p
netProfitForProducts = netProfit products
taxForProducts = tax netProfitForProducts
同样,在计算用户的忠诚度折扣时,需要先计算用户的总消费金额,再根据总消费金额确定忠诚度类别。
userSpend = (user) ->
spend = 100
loyaltyDiscount = (spend) ->
if spend < 1000 then 0
else if spend < 5000 then 5
else if spend < 10000 then 10
else if spe
超级会员免费看
订阅专栏 解锁全文
17

被折叠的 条评论
为什么被折叠?



