【问题标题】:How to select an object from an array where a certain property is minimal?如何从某个属性最小的数组中选择一个对象?
【发布时间】:2012-02-24 01:45:24
【问题描述】:

我刚刚开始了解 Coffescript,并且遇到了从特定属性最少的数组中选择对象的要求。我在下面列出了我的基本代码:

class Point
    constructor: (@x, @y, @z) ->

    addedTogether: ->
        @x+@y+@z

class PointCollection
    constructor: ->
        @points = []

    add: (point) ->
        @points.push(point)

    minimalPoint: ->
        // need to return point with lowest addedTogether value

samplePoints = new PointCollection()
samplePoints.add(new Point(1,2,3))
samplePoints.add(new Point(2,3,4))
samplePoints.add(new Point(3,4,5))
samplePoints.add(new Point(4,5,6))
samplePoints.add(new Point(5,6,7))
samplePoints.add(new Point(1,1,1))

lowestValuePoint = samplePoints.minimalPoint()

我显然可以在普通的旧 javascript 中使用如下函数来做到这一点:

function findPointWithLowestScore(points) {
    var lowestScoringPoint = points[0];

    for (var i = 0; i < points.length; i++) {

    lowestScoringPoint = (points[i].addedTogether() < lowestScoringPoint.addedTogether()) ? points[i] :    lowestScoringPoint;
    }
    return lowestScoringPoint;
}

但是有没有更好、更干净、CoffeeScript-y 的方式来做到这一点?

【问题讨论】:

    标签: javascript arrays coffeescript


    【解决方案1】:

    你可以试试这个:

    class PointCollection
        # ...
        compare: (p1, p2) -> p1.addedTogether() - p2.addedTogether()
    
        minimalPoint: ->
            minPoint = points[0]
            minVal = if compare(minPoint, point) > 0 then point else minPoint for point in points
    

    【讨论】:

      【解决方案2】:

      试试这样的:

      class Point
          constructor: (@x, @y, @z) ->
      
          addedTogether: ->
              @x+@y+@z
      
      class PointCollection
          constructor: ->
              @points = []
      
          add: (point) ->
              @points.push(point)
      
          minimalPoint: ->
              tmp = @points.slice 0 # duplicate array
              tmp.sort (a, b) -> a.addedTogether() - b.addedTogether() # Sort from lowest to highest
              tmp[0] # Return the first element
      
      samplePoints = new PointCollection()
      samplePoints.add(new Point(1,2,3))
      samplePoints.add(new Point(2,3,4))
      samplePoints.add(new Point(3,4,5))
      samplePoints.add(new Point(4,5,6))
      samplePoints.add(new Point(5,6,7))
      samplePoints.add(new Point(1,1,1))
      
      lowestValuePoint = samplePoints.minimalPoint()
      

      【讨论】:

      • 这很好,谢谢,tmp= @points.slice 0 行可以替换为 tmp = @points[..] ,这是同一件事的简写,但我认为读起来更好。
      猜你喜欢
      • 1970-01-01
      • 2017-05-13
      • 2020-11-08
      • 2019-12-03
      • 2020-02-20
      • 2010-10-29
      • 2015-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多