2014-11-21 85 views
4

我想从流星集合中获得一个随机排序的集合。什么是最好的/最有效的方法?流星排序集合随机

Mongo options are controversial

我目前使用underscore _.shuffle这是相当整齐,如:

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

我用玉,所以也许有在模板级别的选项?

+0

问题:既然你在你的模板中使用了一个数组而不是一个光标,它仍然是被动的? – 2014-11-21 14:10:04

+0

@Kyll,是的,但是如果对集合进行更新,整个帮助程序将被重新计算,所以没有很好的细化更新,这可能会也可能不是问题。 – 2014-11-21 15:08:54

+0

这是我找到的最佳解决方案,我认为没有更好的方法来实现相同。 – SsouLlesS 2015-07-22 21:15:48

回答

0

你可以使用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进行了较深入了解比较这两个库。

Underscore和Lo-Dash都使用Fisher-Yates shuffle,你会比“更好”做的更困难。