我只是围绕着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方式呢?
答案 0 :(得分: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()
答案 1 :(得分:0)
你可以试试这个:
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