我有一个函数,它将一个数字显示为一个格式正确的价格(美元)。
var showPrice = (function() {
var commaRe = /([^,$])(\d{3})\b/;
return function(price) {
var formatted = (price < 0 ? "-" : "") + "$" + Math.abs(Number(price)).toFixed(2);
while (commaRe.test(formatted)) {
formatted = formatted.replace(commaRe, "$1,$2");
}
return formatted;
}
})();据我所知,重复使用的正则表达式应该存储在一个变量中,以便它们只编译一次。假设这仍然是真的,那么应该如何在Coffeescript中重写这段代码?
发布于 2013-01-08 04:29:28
这在CoffeeScript中是等效的。
showPrice = do ->
commaRe = /([^,$])(\d{3})\b/
(price) ->
formatted = (if price < 0 then "-" else "") + "$" + Math.abs(Number price).toFixed(2)
while commaRe.test(formatted)
formatted = formatted.replace commaRe, "$1,$2"
formatted发布于 2013-01-08 04:31:38
您可以使用js2coffee将JavaScript代码转换为CoffeeScript。对于给定的代码,结果是:
showPrice = (->
commaRe = /([^,$])(\d{3})\b/
(price) ->
formatted = ((if price < 0 then "-" else "")) + "$" + Math.abs(Number(price)).toFixed(2)
formatted = formatted.replace(commaRe, "$1,$2") while commaRe.test(formatted)
formatted
)()我自己的版本是:
showPrice = do ->
commaRe = /([^,$])(\d{3})\b/
(price) ->
formatted = (if price < 0 then '-' else '') + '$' +
Math.abs(Number price).toFixed(2)
while commaRe.test formatted
formatted = formatted.replace commaRe, '$1,$2'
formatted至于重复使用的正则表达式,我不知道。
https://stackoverflow.com/questions/14203348
复制相似问题