Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add assertion utility function #1602

Merged
merged 3 commits into from
Sep 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/bezier-react/src/utils/assertUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
function isDev() {
return process.env.NODE_ENV !== 'production'
}

export function warn(message: string) {
if (isDev()) {
// eslint-disable-next-line no-console
console.warn(message)
}
}

class AssertionException extends Error {
constructor(message?: string) {
super()

this.name = 'AssertionException'
this.message = message ?? 'assertion failed'
}
}

export function assert(
predicate: boolean,
message?: string,
): asserts predicate {
if (predicate) {
return
}

if (isDev()) {
throw new AssertionException(message)
}
}
9 changes: 6 additions & 3 deletions packages/bezier-react/src/utils/reactUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React from 'react'

import { assert } from './assertUtils'

export const getReactVersion = () => {
const [major, minor, patch] = React.version.split('.').map(Number)
return { major, minor, patch }
Expand Down Expand Up @@ -33,9 +35,10 @@ export function createContext<ContextValue extends StrictContextValue>(
function useContext(consumerName?: any) {
const contextValue = React.useContext(Context)

if (contextValue === null) {
throw new Error(`'${consumerName}' must be used within '${providerName}'`)
}
assert(
contextValue !== null,
`'${consumerName}' must be used within '${providerName}'`,
)

return contextValue
}
Expand Down