本文介绍了Coffeescript记忆化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,以正确的价格(以美元为单位)显示数字。

I have a function that displays a number as a properly formatted price (in USD).

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中重写该代码?

From what I've been told, repeatedly used regexes should be stored in a variable so they are compiled only once. Assuming that's still true, how should this code be rewritten in Coffeescript?

推荐答案

在CoffeeScript中这是等效的

This is the equivalent in 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

这篇关于Coffeescript记忆化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-10 23:53