流星排序集合随机

Kin*_*Guy 5 sorting random meteor

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

Mongo 选项是有争议的

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

Template.userList.helpers({
  users: function() {
    return _.shuffle(Meteor.users.find().fetch());
  }
});
Run Code Online (Sandbox Code Playgroud)

我使用 Jade,所以也许模板级别有一个选项?

Jes*_*sse 0

您可以使用Lodash _.shuffle,如下所示:

Template.userList.helpers({
  users: function() {
    return _.shuffle(Meteor.users.find().fetch());
  }
});
Run Code Online (Sandbox Code Playgroud)

尽管这看起来很搞笑,但本质上是有区别的:

下划线来源

_.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;
};
Run Code Online (Sandbox Code Playgroud)

Lo-Dash为便于比较而稍作修改来源

_.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;
}
Run Code Online (Sandbox Code Playgroud)

您可以查看此 SO 讨论,以更深入地比较这两个库。

Underscore 和 Lo-Dash 都使用Fisher-Yates 洗牌法,你很难做得“更好”。