A big collection of tiny bit hacks from your tiny bit buddy!
npm install bitbob
powershell
pnpm i bitbob
`
While there are bit hacks for algorithms like max or min, implementing them in JS and providing them as a function is slower than the actual built-in Math functions that directly call C++ code. Some bit hacks are so small that they are hard to use as a function because of typical function overhead. Therefore, here is a compiled list of other tiny math optimizations through bit hacks you can do: List
$3
Data structures sometimes come with a very complex lifecycle to, for example, handle user input. Instead of creating dozens of boolean properties for each and every single state, we can compact everything to ONE number.
`typescript
import { BitMap, createBitmapStates } from 'bitbob'
// This creates a LUT (lookup table) for the Bitmap structure to work with.
// The values of the parsed array are the keys and each key-value pair is a different power of 2, depending on the order of the given keys.
const States = createBitmapStates([
'Starting', // 0b1
'Closing', // 0b10
'Scrolling' // 0b100
'Zooming', // 0b1000
'Traversing', // 0b10000
'Passthrough' // 0b100000
])
export default class Component {
states = new BitMap()
update() {
// Checks for one state
if (this.states.has(States.Closing)) return cleanup()
// Checks for multiple states at once. This reduces the number of needed checks as this is an AND operation!
else if (this.states.isMet(States.Scrolling | States.Zooming)) { // = 12 = 1100
// has can also check for multiple states at once, acting as an OR operation!
if (this.states.has(States.Traversing | States.Passthrough))
this.move()
}
}
scroll() {
// Each set state is isolated from another and can not interfere with others.
this.states.set(States.Scrolling)
}
zoom() {
this.states.set(States.Zooming)
}
close() {
this.states.set(States.Closing)
}
}
`
This is not everything. You can also store numbers inside numbers!
`typescript
import { ComposedNumber } from 'bitbob'
function handleScreenRes(data: number) {
// Apply bit maks to extract values without much performance issues.
const height = data & 0x3FF // Width = 1020 AND 10 bit mask
const width = data >> 10 & 0x7FF // Height = 1980 AND 11 bit mask plus shift to right from previous number
return //...
}
// ComposedNumber takes care that each given number is stored properly without collisions
const cn = new ComposedNumber()
cn.set(1020)
cn.set(1980)
handleScreenRes(cn.state)
``