[Exploration] Switch expression #307
aleclarson
started this conversation in
Ideas
Replies: 1 comment 1 reply
-
In current proposal, const config = match(environment, {
production: { apiUrl: 'https://example.com', debug: false },
staging: { apiUrl: 'https://staging.example.com', debug: true },
}, { apiUrl: 'https://dev.example.com', debug: true }) Another concern I have is that people could start to use it inside React components, e.g: const MyComponent = (props) => {
const styles = match(props.status, {
success: { color: "green" },
error: { color: "red" },
}, {})
return <Icon styles={styles} />
} In such case, const styleMatcher = createMatcher({
success: { color: "green" },
error: { color: "red" },
}, {});
const style = styleMatcher(status); P.S. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
It can be useful to have a utility that acts like
switch
but can be used in an expression. This thread is exploring the possible APIs for such a task. Others are encouraged to pitch their own ideas.My idea:
match()
Pass an input value first, followed by an object whose keys are matched against the input value. If a matching key is found, that key's value is returned. If no match is found, and the object has a
default
property, its value will be returned. If still no match is found, returnundefined
.Example usage
If you tried to do similar without
match
, you might try:…which might be “good enough”. Having the “input” come after the named outputs and before the default output is a bit jarring, though.
Here's the equivalent ternary expression (formatted with Biome):
Imagine the objects having more properties, thus needing to be split into multiple lines. It quickly becomes an unpleasant DX.
Beta Was this translation helpful? Give feedback.
All reactions