BitMap的Go和JS实现

五一有空,看了下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));
}

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,497评论 2 59
  • 转自:Go 内存分配器的设计与实现 系统设计、微服务架构和云原生技术](https://mp.weixin.qq....
    雪上霜阅读 2,750评论 0 0
  • 最近在面试,总结总结遇到的面试题. 基础问题 LRU算法 [内存管理]的一种页面置换算法,对于在内存中但又不用的[...
    在牛魔角上狂码阅读 5,656评论 0 0
  • 转载自:超详细的讲解Go中如何实现一个协程池 并发(并行),一直以来都是一个编程语言里的核心主题之一,也是被开发者...
    紫云02阅读 4,707评论 0 1
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    余生动听阅读 13,589评论 0 11