From 7483cae752b2795989f9e8b95e1262bcdca0bdb7 Mon Sep 17 00:00:00 2001 From: Atul Madhugiri Date: Thu, 2 Nov 2023 19:52:41 -0400 Subject: [PATCH] [lib] Introduce `invertObjectToMap` Summary: Context: https://linear.app/comm/issue/ENG-5640/consider-introducing-invertobjecttomap-utility-fn Thanks @tomek for investigating + resolving the flow issues with this utility! Test Plan: Consumed in `minimally-encoded-thread-permissions`, where the unit tests continue to succeed. Reviewers: ashoat, tomek, ginsu, rohan Reviewed By: ashoat Subscribers: wyilio, tomek Differential Revision: https://phab.comm.dev/D9676 --- .../minimally-encoded-thread-permissions.js | 21 ++++++++----------- lib/utils/objects.js | 9 ++++++++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/lib/permissions/minimally-encoded-thread-permissions.js b/lib/permissions/minimally-encoded-thread-permissions.js index 3bd0f8085c..bcdf94dd00 100644 --- a/lib/permissions/minimally-encoded-thread-permissions.js +++ b/lib/permissions/minimally-encoded-thread-permissions.js @@ -7,7 +7,7 @@ import type { ThreadPermission, ThreadPermissionsInfo, } from '../types/thread-permission-types.js'; -import { entries } from '../utils/objects.js'; +import { entries, invertObjectToMap } from '../utils/objects.js'; // `baseRolePermissionEncoding` maps permission names to indices. // These indices represent the 6-bit basePermission part of the 10-bit role @@ -126,21 +126,18 @@ const rolePermissionToBitmaskHex = (threadRolePermission: string): string => { return bitmask.toString(16).padStart(3, '0'); }; -const inverseBaseRolePermissionEncoding = new Map( - Object.entries(baseRolePermissionEncoding).map(([key, value]) => [ - value, - key, - ]), +const inverseBaseRolePermissionEncoding = invertObjectToMap( + baseRolePermissionEncoding, ); // $FlowIssue bigint-unsupported -const inversePropagationPrefixes: Map = new Map( - Object.entries(propagationPrefixes).map(([key, value]) => [value, key]), -); +const inversePropagationPrefixes: Map = + invertObjectToMap(propagationPrefixes); + // $FlowIssue bigint-unsupported -const inverseFilterPrefixes: Map = new Map( - Object.entries(filterPrefixes).map(([key, value]) => [value, key]), -); +const inverseFilterPrefixes: Map = + invertObjectToMap(filterPrefixes); + const decodeRolePermissionBitmask = (bitmask: string): string => { const bitmaskInt = BigInt(`0x${bitmask}`); const basePermission = (bitmaskInt >> BigInt(4)) & BigInt(63); diff --git a/lib/utils/objects.js b/lib/utils/objects.js index 4bc05d7887..0a96ab18f8 100644 --- a/lib/utils/objects.js +++ b/lib/utils/objects.js @@ -129,6 +129,14 @@ function assertObjectsAreEqual( ); } +function invertObjectToMap(obj: { +[K]: V }): Map { + const invertedMap = new Map(); + for (const key of Object.keys(obj)) { + invertedMap.set(obj[key], key); + } + return invertedMap; +} + export { findMaximumDepth, values, @@ -137,4 +145,5 @@ export { assertObjectsAreEqual, deepDiff, entries, + invertObjectToMap, };