How to create an unique room ( room id ) in socket.io for two users?

I want to create an unique room id based on two users ids or emails. Those two users are going to chat with each other. I’ve already made login system (node+express+handlebars). When certain user enters private chat with another user I want to create a room based on their ids, so when that other user does the same procedure he will join same room because it is based on their ids. I’ve tried combining their ids by multiplying them. Example user1(id = 25), user2(id = 4) => roomId = 25*4 = 100. But there is a flaw if two other users with ids 20 and 5 try to chat they will have same roomId.

Answer

Convert your numeric ids to strings and zero pad them to a fixed length. Then combine the two strings together and you will have a unique name based on the two user’s ids. If you want it 100% reproducible, then make sure the lower number id comes first so the two are always in the same relative order.

function createRoomName(id1, id2) {
    // make sure id1 is the smaller value for
    // consistency of generation
    if (id1 > id2) {
        // swap two values
        let temp = id2;
        id2 = id1;
        id1 = temp;
    }
    return id1.toString(10).padStart(10, "0") + id2.toString(10).padStart(10, "0");
}

console.log(createRoomName(35, 19));

Or, you can just put a unique character between the two sets of digits rather than using the padding such as:

function createRoomName(id1, id2) {
    // make sure id1 is the smaller value for
    // consistency of generation
    if (id1 > id2) {
        // swap two values
        let temp = id2;
        id2 = id1;
        id1 = temp;
    }
    return id1 + "|" + id2;
}

console.log(createRoomName(35, 19));

FYI, the reason for the padding or the separator character is that something like:

2,2222

and

22,222

would both generate "22222" which would conflict.

FYI, if you use the actual socket.io generated socket.id for the two users instead of your own number, then those are already unique strings of a certain length and you can directly combine them as strings to get a unique room name.