Skip to content

Commit

Permalink
perf: allow lazy instantiation of invariant message
Browse files Browse the repository at this point in the history
  • Loading branch information
sarahdayan committed Jul 20, 2021
1 parent bf98f25 commit 1d50f0c
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 6 deletions.
2 changes: 1 addition & 1 deletion packages/autocomplete-core/src/resolve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ export function postResolve<TItem extends BaseItem>(

invariant(
Array.isArray(items),
`The \`getItems\` function from source "${
() => `The \`getItems\` function from source "${
source.sourceId
}" must return an array of items but returned type ${JSON.stringify(
typeof items
Expand Down
7 changes: 4 additions & 3 deletions packages/autocomplete-core/src/utils/getNormalizedSources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@ export function getNormalizedSources<TItem extends BaseItem>(
return Promise.resolve(getSources(params)).then((sources) => {
invariant(
Array.isArray(sources),
`The \`getSources\` function must return an array of sources but returned type ${JSON.stringify(
typeof sources
)}:\n\n${JSON.stringify(decycle(sources), null, 2)}`
() =>
`The \`getSources\` function must return an array of sources but returned type ${JSON.stringify(
typeof sources
)}:\n\n${JSON.stringify(decycle(sources), null, 2)}`
);

return Promise.all(
Expand Down
17 changes: 17 additions & 0 deletions packages/autocomplete-shared/src/__tests__/invariant.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,22 @@ describe('invariant', () => {
invariant(true, 'invariant');
}).not.toThrow();
});

test('lazily instantiates message', () => {
const spy1 = jest.fn(() => 'invariant');
const spy2 = jest.fn(() => 'invariant');

expect(() => {
invariant(false, spy1);
}).toThrow('[Autocomplete] invariant');

expect(spy1).toHaveBeenCalledTimes(1);

expect(() => {
invariant(true, spy2);
}).not.toThrow('[Autocomplete] invariant');

expect(spy2).not.toHaveBeenCalled();
});
}
});
9 changes: 7 additions & 2 deletions packages/autocomplete-shared/src/invariant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,17 @@
* This is used to make development a better experience to provide guidance as
* to where the error comes from.
*/
export function invariant(condition: boolean, message: string) {
export function invariant(
condition: boolean,
message: string | (() => string)
) {
if (!__DEV__) {
return;
}

if (!condition) {
throw new Error(`[Autocomplete] ${message}`);
const _message = typeof message === 'string' ? message : message();

throw new Error(`[Autocomplete] ${_message}`);
}
}

0 comments on commit 1d50f0c

Please sign in to comment.