如何重构 Coffeescript/Javascript 列表中的重复字段?

How to refactor repeated fields in a list in Coffeescript/Javascript?

代码如下所示:

  $scope.markerList = [
    {
      id: 1
      pos:
        latitude: 45
        longitude: -73
      options: {animation: map.Animation.DROP}

    }
    {
      id: 2
      pos:
        latitude: 44.5
        longitude: -72.7
      options: {animation: map.Animation.DROP}
    }
    {
      id: 3
      pos:
        latitude: 44.6
        longitude: -72.6
      options: {animation: map.Animation.DROP}

    }
    {
      id: 4
      pos:
        latitude: 44.95
        longitude: -72.95
      options: {animation: map.Animation.DROP}

    }

  ]

可以看出,列表的每个元素都有相同的字段,如options:{...}。有没有更简单的方法在 Coffeescript 中编写此列表?

也许是这样的:

$scope.markerList = [{
  id: 1,
  pos: {
    latitude: 45,
    longitude: -73
  }
}, {
  id: 2,
  pos: {
    latitude: 44.5,
    longitude: -72.7
  }
}, {
  id: 3,
  pos: {
    latitude: 44.6,
    longitude: -72.6
  }
}, {
  id: 4,
  pos: {
    latitude: 44.95,
    longitude: -72.95
  }
}].map(function(marker) {
  marker.options = {animation: map.Animation.DROP};
  return marker;
});

您可以为列表中的项目创建一个 class,它可能看起来像这样:

class Marker
  id = 0
  constructor: (lat, long, animation) ->
    @id = ++id
    @position =
      latitude: lat
      longitude: long
    @options = 
      animation: animation

然后您将用 class:

的实例填充您的 markerList
defaultAnimation = map.Animation.DROP

$scope.markerList = [
    new Marker(45, -73, defaultAnimation)
    new Marker(44.5, -72.7, defaultAnimation)
    new Marker(44.6, -72.6, defaultAnimation)
    new Marker(44.95, -72.95, defaultAnimation)
]

假设 map 是全局的(或者更好的是,你可以通过 DI 注入的东西),你甚至可以考虑将 defaultAnimation 添加到构造函数中,这将进一步简化它:

class Marker
  id = 0
  constructor: (lat, lng, animation = map.Animation.DROP) ->
    ...

$scope.markerList = [
    new Marker(45, -73)
    new Marker(44.5, -72.7)
    ...
]

我会这样做: (注意 - 根据下面的评论,我对此进行了编辑以修复缩进。)

points = [
  [1, 45, -73]
  [2, 44.5, -72.7]
  [3, 44.6, -72.6]
  [4, 44.95, -72.95] ]

sml = []

for p in points
  pp = {
    id: p[0]
    pos:
      latitude: p[1]
      longitude: p[2]
    options: {animation: map.Animation.DROP} }

  sml.push(pp)

$scope.markerList = sml