问题描述
我想从Meteor集合中获得随机排序的集合.最好/最有效的方法是什么?
I want to get a randomly sorted set from a Meteor collection. What is the best/most efficient way?
我当前正在使用下划线_.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 (稍作修改以便于比较,源)
_.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;
}
您可以查看此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.
这篇关于流星分类收集随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!