Skip to content

Commit

Permalink
Merge pull request #550 from callstack-internal/hur/perf/use-set-foreach
Browse files Browse the repository at this point in the history
perf: use ForEach method from Set instead of manual loop operations
  • Loading branch information
mountiny authored Jun 19, 2024
2 parents 04928a9 + 0ee1261 commit 43fc634
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 11 deletions.
9 changes: 7 additions & 2 deletions lib/Onyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,13 @@ function connect<TKey extends OnyxKey>(connectOptions: ConnectOptions<TKey>): nu
// We search all the keys in storage to see if any are a "match" for the subscriber we are connecting so that we
// can send data back to the subscriber. Note that multiple keys can match as a subscriber could either be
// subscribed to a "collection key" or a single key.
const matchingKeys = Array.from(keys).filter((key) => OnyxUtils.isKeyMatch(mapping.key, key));

const matchingKeys: string[] = [];
keys.forEach((key) => {
if (!OnyxUtils.isKeyMatch(mapping.key, key)) {
return;
}
matchingKeys.push(key);
});
// If the key being connected to does not exist we initialize the value with null. For subscribers that connected
// directly via connect() they will simply get a null value sent to them without any information about which key matched
// since there are none matched. In withOnyx() we wait for all connected keys to return a value before rendering the child
Expand Down
15 changes: 6 additions & 9 deletions lib/OnyxUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,17 +327,14 @@ function tryGetCachedValue<TKey extends OnyxKey>(key: TKey, mapping?: Partial<Wi
return;
}

const matchingKeys = Array.from(allCacheKeys).filter((k) => k.startsWith(key));
const values = matchingKeys.reduce((finalObject: NonNullable<OnyxCollection<KeyValueMapping[TKey]>>, matchedKey) => {
const cachedValue = cache.get(matchedKey);
if (cachedValue) {
// This is permissible because we're in the process of constructing the final object in a reduce function.
// eslint-disable-next-line no-param-reassign
finalObject[matchedKey] = cachedValue;
const values: OnyxCollection<KeyValueMapping[TKey]> = {};
allCacheKeys.forEach((cacheKey) => {
if (!cacheKey.startsWith(key)) {
return;
}
return finalObject;
}, {});

values[cacheKey] = cache.get(cacheKey);
});
val = values;
}

Expand Down

0 comments on commit 43fc634

Please sign in to comment.