【问题标题】:Meteor sort collection random流星排序集合随机
【发布时间】:2015-01-19 14:15:36
【问题描述】:

我想从 Meteor 集合中获得一个随机排序的集合。什么是最好/最有效的方法?

Mongo options are controversial

我目前正在使用underscore _.shuffle,它非常简洁,例如:

Template.userList.helpers({
  users: function() {
    return _.shuffle(Meteor.users.find().fetch());
  }
});

我使用 Jade,所以在模板级别可能有一个选项?

【问题讨论】:

  • 问题:由于您在模板中使用的是数组而不是游标,它仍然是响应式的吗?
  • @Kyll,是的,但是如果对集合进行更新,整个帮助程序将被重新计算,因此没有很好的细粒度更新,这可能是也可能不是问题。
  • 这是我找到的最好的解决方案,我认为没有更好的方法来达到同样的效果。

标签: sorting random meteor


【解决方案1】:

你可以使用Lodash _.shuffle,像这样:

Template.userList.helpers({
  users: function() {
    return _.shuffle(Meteor.users.find().fetch());
  }
});

虽然看起来很搞笑,但其实是有区别的:

下划线 (source)

_.shuffle = function(obj) {
  var set = isArrayLike(obj) ? obj : _.values(obj);
  var length = set.length;
  var shuffled = Array(length);
  for (var index = 0, rand; index < length; index++) {
    rand = _.random(0, index);
    if (rand !== index) shuffled[index] = shuffled[rand];
    shuffled[rand] = set[index];
  }
  return shuffled;
};

Lo-Dash为了便于比较而稍作修改source

_.shuffle = function(collection) {
  MAX_ARRAY_LENGTH = 4294967295;
  return sampleSize(collection, MAX_ARRAY_LENGTH);
}

function sampleSize(collection, n) {
  var index = -1,
      result = toArray(collection),
      length = result.length,
      lastIndex = length - 1;

  n = clamp(toInteger(n), 0, length);
  while (++index < n) {
    var rand = baseRandom(index, lastIndex),
        value = result[rand];

    result[rand] = result[index];
    result[index] = value;
  }
  result.length = n;
  return result;
}

您可以查看this SO discussion,以更深入地了解比较这两个库。

Underscore 和 Lo-Dash 都使用 Fisher-Yates shuffle,你很难做得比它“更好”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-24
    • 1970-01-01
    • 2016-05-10
    • 2013-02-15
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    相关资源
    最近更新 更多