-
Notifications
You must be signed in to change notification settings - Fork 9
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
Conditional Cases #13
base: master
Are you sure you want to change the base?
Conversation
f0bd7ed
to
d9782b0
Compare
will try this package after you merge this. 📦 |
Hey @ajwhite. This looks pretty good to me. If you want to get rid of evaluate why not just return the evaluate function with the api attached? renderIf.switch(x)();
renderif.switch(x)
.case(1)(<span>1</span>)
.case(2)(<span>2</span>)
.default(<span>default</span>)(); also i noticed that you are sorting conditions by 'type' before evaluating them, presumably because you'd like to make sure conditions are executed in the proper order. I think it might be better to enforce the behavior you want instead of fixing invalid usages of the library and causing potentially unexpected results. I think the easiest way to do this would be to follow a builder type approach and create a funnel. Maybe something along these lines. const multi = () => {
const cases = [];
function createEvaluator() {
return function evaluate() {
for (let index = 0; index < cases.length; index++) {
if (cases[index].condition) {
if (typeof cases[index].elemOrThunk === 'function') {
return cases[index].elemOrThunk();
}
return cases[index].elemOrThunk;
}
}
return null;
};
};
function ifCondition (condition) {
return (elemOrThunk) => {
cases.push({ condition, elemOrThunk });
return ifConditionApi;
};
};
function elseCondition (elemOrThunk) {
cases.push({ condition: true, elemOrThunk });
return createEvaluator();
};
const ifConditionApi = Object.assign(
createEvaluator(),
{
else: elseCondition,
elseIf: ifCondition
}
);
return { if: ifCondition };
};
const renderIf = () => {};
renderIf.if = (condition) => multi().if(condition);
renderIf
.if(false)('if condition')
.elseIf(false)('else')
.elseIf(false)('another else')
.else('hello')();
renderIf
.if(false)('if condition')
.else('hi')();
renderIf
.if(false)('if condition')
.else('hi')
.elseIf(true)('ERROR!!11!!one!')(); |
Very handy, I like it! Any plans to merge? |
Seeking Feedback
I'd love to hear from some folks that currently use this, or are interested in using this, in what they think of the approaches behind these two new APIs.
Here we are -- support for multiple cases (#7):
If/ElseIf/Else
Instead of:
Note: this does not remove
renderIf
- it's still quite handy and can be used for single conditionsSwitch
I'd love if we didn't have to call
evaluate()
- but I can't imagine it's possible to know when we're at the end of the execution chain.Tests are still needed for this PR