Skip to content

Instantly share code, notes, and snippets.

@o0
Created June 16, 2020 17:28
Show Gist options
  • Save o0/bf85a4d13dbb23a532e13443c73808fd to your computer and use it in GitHub Desktop.
Save o0/bf85a4d13dbb23a532e13443c73808fd to your computer and use it in GitHub Desktop.
const addState = (initialState, newState) => {
return initialState | newState;
};
const removeState = (initialState, stateToRemove) => {
return ~initialState & stateToRemove;
};
const hasState = (initialState, stateToCheck) => {
return Boolean(initialState & stateToCheck);
};
// Example
const State = {
HOVERED: 0b01, // One
FOCUSED: 0b10, // Two
DISABLED: 0b100, // Four
};
const DEFAULT_STATE = 0b00;
let state = DEFAULT_STATE;
state = addState(state, State.HOVERED); // 0b01
console.log(hasState(state, State.HOVERED)); // true
console.log(hasState(state, State.FOCUSED)); // false
state = removeState(state, State.HOVERED); // 0b00;
console.log(hasState(state, State.HOVERED)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment