Skip to content

Commit

Permalink
[lib] Introduce invertObjectToMap
Browse files Browse the repository at this point in the history
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
  • Loading branch information
atulsmadhugiri committed Nov 3, 2023
1 parent 4082f25 commit 7483cae
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
21 changes: 9 additions & 12 deletions lib/permissions/minimally-encoded-thread-permissions.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<bigint, string> = new Map(
Object.entries(propagationPrefixes).map(([key, value]) => [value, key]),
);
const inversePropagationPrefixes: Map<bigint, string> =
invertObjectToMap(propagationPrefixes);

// $FlowIssue bigint-unsupported
const inverseFilterPrefixes: Map<bigint, string> = new Map(
Object.entries(filterPrefixes).map(([key, value]) => [value, key]),
);
const inverseFilterPrefixes: Map<bigint, string> =
invertObjectToMap(filterPrefixes);

const decodeRolePermissionBitmask = (bitmask: string): string => {
const bitmaskInt = BigInt(`0x${bitmask}`);
const basePermission = (bitmaskInt >> BigInt(4)) & BigInt(63);
Expand Down
9 changes: 9 additions & 0 deletions lib/utils/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,14 @@ function assertObjectsAreEqual<K, T>(
);
}

function invertObjectToMap<K, V>(obj: { +[K]: V }): Map<V, K> {
const invertedMap = new Map<V, K>();
for (const key of Object.keys(obj)) {
invertedMap.set(obj[key], key);
}
return invertedMap;
}

export {
findMaximumDepth,
values,
Expand All @@ -137,4 +145,5 @@ export {
assertObjectsAreEqual,
deepDiff,
entries,
invertObjectToMap,
};

0 comments on commit 7483cae

Please sign in to comment.