CoffeeScript的记忆化?(Coffeescript memoization?)

2019-10-17 13:32发布

我有一个显示号码为格式正确的价格(美元)的功能。

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重写?

Answer 1:

这是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


Answer 2:

您可以使用翻译JavaScript代码到CoffeeScript的js2coffee 。 对于给定的代码,结果是:

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

至于多次使用正则表达式,我不知道。



文章来源: Coffeescript memoization?