Coffeescript memoization?

妖精的绣舞 提交于 2020-02-25 10:11:12

问题


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;
  }
})();

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?


回答1:


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



回答2:


You can translate your JavaScript code into CoffeeScript using js2coffee. For given code the result is:

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
)()

My own version is:

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

As for repeatedly used regexes, I don't know.



来源:https://stackoverflow.com/questions/14203348/coffeescript-memoization

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!