我想从 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/