首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Coffeescript memoization

Coffeescript memoization
EN

Stack Overflow用户
提问于 2013-01-08 04:15:24
回答 2查看 1.2K关注 0票数 1

我有一个函数,它将一个数字显示为一个格式正确的价格(美元)。

代码语言:javascript
复制
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中重写这段代码?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-01-08 04:29:28

这在CoffeeScript中是等效的。

代码语言:javascript
复制
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
票数 4
EN

Stack Overflow用户

发布于 2013-01-08 04:31:38

您可以使用js2coffee将JavaScript代码转换为CoffeeScript。对于给定的代码,结果是:

代码语言:javascript
复制
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
)()

我自己的版本是:

代码语言:javascript
复制
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

至于重复使用的正则表达式,我不知道。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14203348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档