Skip to content

Commit 73dc1c2

Browse files
committed
Modify forEachEnvelopeItem so it can be exited early
1 parent 1b6a28d commit 73dc1c2

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

packages/utils/src/envelope.ts

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,31 +41,32 @@ export function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1]
4141
/**
4242
* Convenience function to loop through the items and item types of an envelope.
4343
* (This function was mostly created because working with envelope types is painful at the moment)
44+
*
45+
* If the callback returns true, the rest of the items will be skipped.
4446
*/
4547
export function forEachEnvelopeItem<E extends Envelope>(
4648
envelope: Envelope,
47-
callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => void,
48-
): void {
49+
callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,
50+
): boolean {
4951
const envelopeItems = envelope[1];
50-
envelopeItems.forEach((envelopeItem: EnvelopeItem) => {
52+
53+
for (const envelopeItem of envelopeItems) {
5154
const envelopeItemType = envelopeItem[0].type;
52-
callback(envelopeItem, envelopeItemType);
53-
});
55+
const result = callback(envelopeItem, envelopeItemType);
56+
57+
if (result) {
58+
return true;
59+
}
60+
}
61+
62+
return false;
5463
}
5564

5665
/**
5766
* Returns true if the envelope contains any of the given envelope item types
5867
*/
5968
export function envelopeContainsItemType(envelope: Envelope, ...types: EnvelopeItemType[]): boolean {
60-
let isType = false;
61-
62-
forEachEnvelopeItem(envelope, (_, type) => {
63-
if (types.includes(type)) {
64-
isType = true;
65-
}
66-
});
67-
68-
return isType;
69+
return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));
6970
}
7071

7172
/**

0 commit comments

Comments
 (0)