refactor findUserByDisplayName

This commit is contained in:
pa
2026-03-14 21:43:22 +09:00
parent a314885bff
commit a64f4f6d7a
10 changed files with 195 additions and 24 deletions

View File

@@ -17,6 +17,19 @@ describe('findUserByDisplayName', () => {
return map;
}
function createDisplayNameIndex(entries) {
const index = new Map();
for (const entry of entries) {
let ids = index.get(entry.displayName);
if (!ids) {
ids = new Set();
index.set(entry.displayName, ids);
}
ids.add(entry.id);
}
return index;
}
test('returns the user matching displayName', () => {
const users = createCachedUsers([
{ id: 'usr_1', displayName: 'Alice' },
@@ -56,4 +69,31 @@ describe('findUserByDisplayName', () => {
expect(findUserByDisplayName(users, 'alice')).toBeUndefined();
expect(findUserByDisplayName(users, 'ALICE')).toBeUndefined();
});
test('uses displayName index when provided', () => {
const entries = [
{ id: 'usr_1', displayName: 'Alice' },
{ id: 'usr_2', displayName: 'Bob' }
];
const users = createCachedUsers(entries);
const index = createDisplayNameIndex(entries);
const result = findUserByDisplayName(users, 'Bob', index);
expect(result).toEqual({ id: 'usr_2', displayName: 'Bob' });
});
test('indexed lookup falls back to next duplicate when first user is missing', () => {
const entries = [
{ id: 'usr_1', displayName: 'Alice' },
{ id: 'usr_2', displayName: 'Alice' }
];
const users = createCachedUsers(entries);
users.delete('usr_1');
const index = createDisplayNameIndex(entries);
const result = findUserByDisplayName(users, 'Alice', index);
expect(result).toEqual({ id: 'usr_2', displayName: 'Alice' });
});
});

View File

@@ -275,9 +275,23 @@ function userOnlineFor(ref) {
* Find a user object from cachedUsers by displayName.
* @param {Map} cachedUsers
* @param {string} displayName
* @param {Map<string, Set<string>>} [cachedUserIdsByDisplayName]
* @returns {object|undefined}
*/
function findUserByDisplayName(cachedUsers, displayName) {
function findUserByDisplayName(
cachedUsers,
displayName,
cachedUserIdsByDisplayName
) {
const indexedUserIds = cachedUserIdsByDisplayName?.get(displayName);
if (indexedUserIds) {
for (const userId of indexedUserIds) {
const ref = cachedUsers.get(userId);
if (ref?.displayName === displayName) {
return ref;
}
}
}
for (const ref of cachedUsers.values()) {
if (ref.displayName === displayName) {
return ref;