如何从数组中选择某个属性最小的对象?
我刚刚开始了解 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 的方法来做到这一点?
I'm just getting my head around Coffescript and have come across a requirement to select an object from an array where a particular property is minimal. I've set out my basic code below:
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()
I can obviously do that in plain old javascript with a function like:
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;
}
but is there a nicer, cleaner, CoffeeScript-y way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这样的事情:
Try something like this:
你可以试试这个:
You can try this: