sorting - meteor 排序集合随机

标签 sorting random meteor

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

Mongo options are controversial

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

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

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

最佳答案

您可以使用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更深入地了解这两个库的比较。

下划线和 Lo-Dash 都使用 Fisher-Yates shuffle你很难做得“更好”。

关于sorting - meteor 排序集合随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27061280/

相关文章:

postgresql - 具有随机排序行的可重复分页

meteor 和铁路由器 : raise 404 when id doesn't exist

orm - meteor :与 Mongoose 整合?

javascript - 如何在 Meteor 中从服务器动态更新网页?

javascript - 排序数组,使空值项出现在最后

c# - 在 C# 中使用多个条件和多个变量对列表进行排序

node.js - Node INTL 语言环境排序规则

arrays - 在 Swift 中对多维数组(数组中的数组)使用排序?

c - 普通 C 中的快速随机洗牌功能

java - 为什么这个随机值的分布是 25/75 而不是 50/50?