I have a use case where a user can pass certain number of variables based on which a specific logic will be performed.
As the combination of variables my differ I trying to think about an elegant way to code this process.
For example user can pass either name & type or email && schoolId && type other combinations are not supported.
I was thinking about something like this:
const filterByX = (name && type);
const filterByY = (email && schoolId && type);
const decision = (filterByX ? 'filterX' : (filterByY ? 'filterY' : null ));
switch(decision) {
case 'filterX':
...
break;
case 'filterY':
...
break;
default:
console.log('not supported')
}
But I trust that there's a more elegant way to implement such logic. Would appreciate a suggestion.
One idea is an object keyed with the bitwise combination of variables. For instance, if a, b, c are the input bools, each combo you care about can be encoded as an int 0-7.
const boolsToBits = (a,b,c) => {
return a << 2 | b << 1 | c ;
}
console.log(boolsToBits(true, true, false)) // == 6
With that, you can either switch on the resulting int, or (better, imo) describe functions corresponding to conditions using data - using an object keyed by the resulting ints.
const actions = {
7: () => console.log('a, b and c are true'),
6: () => console.log('a, b are true'),
2: () => console.log('only b is true'),
}
const defaultAction = () => console.log('a combo not coded for explicitly')
const boolsToBits = (a, b, c) => {
return a << 2 | b << 1 | c;
}
const handleThreeBools = (a, b, c) => {
const action = actions[boolsToBits(a, b, c)] || defaultAction;
action();
}
handleThreeBools(true, true, true);
handleThreeBools(true, true, false);
handleThreeBools(false, true, false);
handleThreeBools(false, true, true);
The idea can be generalized for an arbitrary number of bools like this...
const actions = {
7: () => console.log('a, b and c are true'),
6: () => console.log('a, b are true'),
2: () => console.log('only b is true'),
33: () => console.log('thats a lot of bits!')
}
const defaultAction = () => console.log('a combo not coded for explicitly')
const boolsToBitsN = (...args) => {
const length = args.length;
let result = 0;
for (let i = 0; i < length; i++) result |= args[i] << (length - 1 - i);
return result
}
const handleNBools = (...args) => {
const action = actions[boolsToBitsN(...args)] || defaultAction;
action();
}
handleNBools(true, false, false, false, false, true);
And of course, the object containing functions keyed by ints can expand accordingly.