Last active
December 16, 2020 02:06
-
-
Save wickedev/d1c33eedf2d7e4b697bf6e058920787b to your computer and use it in GitHub Desktop.
Handling complex condition without if statements with bitwise operators and bit masks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
+--------------------------------+---------------+ | |
| type | bitmask | | |
+--------------------------------+---------------+ | |
| mode (light, dark) | 0b0100 | | |
| screen size (xs, sm, md, lg) | 0b0011 | | |
+--------------------------------+---------------+ | |
*/ | |
type Bits = number; | |
const BITMASK_MODE = 0b0100; | |
enum Mode { | |
Light = 0b0000, | |
Dark = 0b0100, | |
} | |
const BITMASK_SCREEN = 0b0011; | |
enum ScreenSize { | |
XS = 0b0000, | |
SM = 0b0001, | |
MD = 0b0010, | |
LG = 0b0011, | |
} | |
const actions = { | |
[Mode.Light | ScreenSize.XS]: function () { | |
return "Light / XS"; | |
}, | |
[Mode.Light | ScreenSize.SM]: function () { | |
return "Light / SM"; | |
}, | |
[Mode.Light | ScreenSize.MD]: function () { | |
return "Light / MD"; | |
}, | |
[Mode.Light | ScreenSize.LG]: function () { | |
return "Light / LG"; | |
}, | |
[Mode.Dark | ScreenSize.XS]: function () { | |
return "Dark / XS"; | |
}, | |
[Mode.Dark | ScreenSize.SM]: function () { | |
return "Dark / SM"; | |
}, | |
[Mode.Dark | ScreenSize.MD]: function () { | |
return "Dark / MD"; | |
}, | |
[Mode.Dark | ScreenSize.LG]: function () { | |
return "Dark / LG"; | |
}, | |
}; | |
interface IConfig { | |
mode: Mode; | |
screenSize: ScreenSize; | |
} | |
test("Handling complex condition without if statements with bitwise operators and bit masks", () => { | |
const config: IConfig = { | |
mode: Mode.Dark, | |
screenSize: ScreenSize.LG, | |
}; | |
const bits = configToBits(config); | |
expect(bits).toBe(0b111); | |
expect(bits & BITMASK_MODE).toBe(0b100); | |
expect(bits & BITMASK_MODE).toBe(Mode.Dark); | |
expect(bits & BITMASK_SCREEN).toBe(0b011); | |
expect(bits & BITMASK_SCREEN).toBe(ScreenSize.LG); | |
expect(createScreen(config)).toBe("Dark / LG"); | |
}); | |
function configToBits(config: IConfig): Bits { | |
let bits = 0b0; | |
for (const key in config) { | |
if (config.hasOwnProperty(key)) { | |
bits |= (config as any)[key]; | |
} | |
} | |
return bits; | |
} | |
function createScreen(config: IConfig) { | |
return actions[configToBits(config)]?.(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment