Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.6 kB
3
Indexable
Never
 const userSessions = {};
    const outputUserIds = new Set();

    logs.forEach(log => {
        const [userId, timestamp, action] = log.split(' ');
        const time = parseInt(timestamp, 10);

        if (!userSessions[userId]) {
            userSessions[userId] = { signIn: [], signOut: [] };
        }

        if (action === 'sign-in') {
            userSessions[userId].signIn.push(time);
        } else {
            userSessions[userId].signOut.push(time);
        }
    });

    // Sort sign-in and sign-out times
    Object.keys(userSessions).forEach(userId => {
        userSessions[userId].signIn.sort((a, b) => a - b);
        userSessions[userId].signOut.sort((a, b) => a - b);
    });

    // Match sign-in and sign-out times
    Object.keys(userSessions).forEach(userId => {
        const signInTimes = userSessions[userId].signIn;
        const signOutTimes = userSessions[userId].signOut;
        let signOutIndex = 0;

        signInTimes.forEach(signInTime => {
            while (signOutIndex < signOutTimes.length && signOutTimes[signOutIndex] < signInTime) {
                signOutIndex++;
            }
            if (signOutIndex < signOutTimes.length) {
                const timeDiff = signOutTimes[signOutIndex] - signInTime;
                if (timeDiff <= maxSpan) {
                    outputUserIds.add(userId);
                }
                signOutIndex++;
            }
        });
    });

    // Convert to array, sort numerically and return
    return Array.from(outputUserIds).sort((a, b) => parseInt(a, 10) - parseInt(b, 10));
Leave a Comment