【问题标题】:How to translate this GorillaScript into LiveScript?如何将此 GorillaScript 翻译成 LiveScript?
【发布时间】:2016-04-03 18:57:38
【问题描述】:

我有这个 GorillaScript 代码来展平数组:

Array::compact  :=  #
  for filter value in this
     value and (typeof value.isempty != 'function' or not value.isempty()) and (typeof value != 'object' or Object.keys(value).length != 0)

GorillaScript 已经死了。有人可以帮我把它翻译成 LiveScript 吗?我对 LiveScript 很陌生。

【问题讨论】:

    标签: translate livescript


    【解决方案1】:

    直译应该是这样的。

    Array.prototype.compact = ->
      [v for v in @ when v and (typeof v.isempty isnt \function or not v.isempty!) and (typeof v isnt \object or Object.keys value .length > 0)]
    

    一个更惯用的例子可能是:

    is-empty = ->
      | not it => false 
      | typeof it.isempty isnt \function or not it.isempty! => true
      | typeof it isnt \object or not Object.keys it .length > 0 => true
      | otherwise => it
    
    Array.prototype.compact = -> [x for x in @ when not is-empty x]
    

    当心,因为这是在我的脑海中完成的,所以我的 LiveScript 有点生锈,但这里的总体思路是可以的。

    【讨论】:

    • 大部分是对的,尽管您在第三行缺少“=>”。但是在调用“[1, null, 2].compact()”时出现错误“null 不是对象(评估 'it.isempty')”
    • 也许在顶部添加一个案例“|不是吗?=> false”?
    • 是的,正如我所说的有点生疏——重要的是一般概念。我猜你的建议相对于原始代码在语义上也会更正确。
    • 感谢您的帮助。
    • empty? 重命名为 is-empty,因为 LS 不允许在标识符中使用标点符号:)。
    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多