I am creating a switch hook that simply have to change (one value) from a to c each time a function is called , meaning that if (a) is true on next click a will be (false) and b will be (true),only one true value at time but in order from a-c (circle), I am kind of confused whether integrating those three values is even good idea rather than making a separate state for each of them any idea how to tackle this?
const [type, setType] = useState < {
a: boolean;b: boolean;c: boolean
} > ({
a: false,
b: false,
c: false
});
const swapType = () => {
// get the current ture
const getTrue = (obj: typeof setType, value: boolean) => {
return Object.keys(obj).find((key) => obj[key] === value);
};
const copyObj = { ...type
};
for (let type in copyObj) {
// Turn of the true !
if (type === getTrue(type, true)) {
copyObj[type] = false;
}
// Turn on following value only
}
setType(copyObj);
};
}
CodePudding user response:
You could accomplish this using some if statements or a switch if this is all you are looking for. I am not sure if you want after c click to go back to triple false or return to a is true. You may need to adjust that code.
const swapType = (t)=>{
if(t.a){
setSetType({ a: false, b: true, c: false });
return
}
if(t.b){
setSetType({ a: false, b: false, c: true });
return
}
if(t.c){
setSetType({ a: true, b: false, c: false });
return
}
setSetType({ a: true, b: false, c: false });
}
CodePudding user response:
I would use a tuple of Boolean values ([boolean, boolean, boolean]
in TypeScript) to do this.
const swapType = (values: [boolean, boolean, boolean]): [boolean, boolean, boolean] => {
values.every(val => !val) ? values = [true, false, false] : values.unshift(values.pop());
return values;
};
console.log(swapType([false, false, false]));
console.log(swapType([true, false, false]));
console.log(swapType([false, true, false]));
console.log(swapType([false, false, true]));