美文网首页
BitMap的Go和JS实现

BitMap的Go和JS实现

作者: ashyanSpada | 来源:发表于2021-05-03 00:32 被阅读0次

五一有空,看了下BitMap的介绍,分别用Go和JS实现了一下。

// Go实现
type BitMap struct {
    store []byte
    max   int64
}

func NewBitMap(max int64) *BitMap {
    return &BitMap{
        store: make([]byte, (max>>3)+1),
        max:   max,
    }
}

func (b *BitMap) Add(num uint) {
    index := num >> 3
    pos := num & 0x07
    b.store[index] |= 1 << pos
}

func (b *BitMap) Has(num uint) bool {
    index := num >> 3
    pos := num & 0x07
    return b.store[index]&(1<<pos) == 1
}

func (b *BitMap) Remove(num uint) {
    index := num >> 3
    pos := num & 0x07
    b.store[index] &= ^(1 << pos)
}
// JS实现
function BitMap(max) {
    this.max = max;
    this.buffer = new ArrayBuffer(max);
    this.view = new DataView(this.buffer);
}

BitMap.prototype.Add = function(num) {
    const index = num >> 3;
    const pos = num & 0x07;
    this.view.setInt8(index, this.view.getInt8(index) & (1 << pos));
}

BitMap.prototype.Has = function(num) {
    const index = num >> 3;
    const pos = num & 0x07;
    return this.view.getInt8(index) & (1 << pos) === 1;
}

BitMap.prototype.Remove = function (num) {
    const index = num >> 3;
    const pos = num & 0x07;
    this.view.setInt8(index, this.view.getInt8(index) & (1<<pos));
}

注意:
大概思路,还未做测试。

相关文章

网友评论

      本文标题:BitMap的Go和JS实现

      本文链接:https://www.haomeiwen.com/subject/tnnxdltx.html