流星分类收集随机 [英] Meteor sort collection random

查看:95
本文介绍了流星分类收集随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get a randomly sorted set from a Meteor collection. What is the best/most efficient way?

Mongo选项存在争议.

我当前正在使用下划线_.shuffle ,它很简洁,例如:

I am currently using underscore _.shuffle which is quite neat, eg:

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

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

I use Jade, so maybe there's an option at the templating level?

推荐答案

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

You could use Lodash _.shuffle, like so:

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

尽管看起来很有趣,但 却有不同之处:

As hilarious as that might seem, there is a difference under the hood:

下划线()

_.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 (稍作修改以便于比较您可以查看此SO讨论,以进行更深入的了解看一下比较这两个库.

You can take a look at this SO discussion for a more in-depth look at comparing the two libraries.

下划线和Lo-Dash均使用 Fisher-Yates随机播放您将很难做到比"更好.

Both, Underscore and Lo-Dash, use the Fisher-Yates shuffle which you'd have a hard time doing "better" than.

这篇关于流星分类收集随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆