保持插座的全局數組並將其過濾與filter
:
var socketList = [];
io.sockets.on("connection", function(socket) {
// add socket to list on connection
socketList.push(socket);
// remove socket from list on disconnect
socket.on("disconnect", function() {
socketList.splice(socketList.indexOf(socket), 1);
});
socket.on('search', function(country) {
// Give list of sockets where (socket.country) = country
var filteredList = socketList.filter(function(s) {
return s.country == country;
});
});
});
如果你有插座的數量龐大且filter
荷蘭國際集團在O(n)的時間過得很慢,你可以改變代碼保持O(1)訪問的查找表,這可能看起來像一個對象,其成員是插座的數組:
{
"USA": [socket, socket, socket, ...],
"Canada": [socket, socket, ...],
...
}
而且你訪問的每個列表與socketLookupTable[countryName]
。