[Immutable.js] Lightning Fast Immutable.js Equality Checks with Hash Codes

本文探讨了使用Immutable.js库中的哈希码进行快速迭代器相等性检查的方法。通过比较不同迭代器的内容生成的哈希码来确认它们是否相等,这种方法虽然高效但存在一定的碰撞风险。

While Immutable.js offers .is() to confirm value equality between iterables it comes at the cost of referencing each key and value in both objects. For lightning fast equality checks, Immutable.js can produce a hash code based on an iterable's content. If two iterables have the same content, their hash codes will be the same. It's worth noting that this technique is unsuitable for mission critical application development since there is a chance, however slight, that checksums like these might collide. This is outlined here: https://en.wikipedia.org/wiki/Collision_(computer_science)

 

mocha.setup('bdd');
const expect = chai.expect;

class Todo {
  
  constructor(title="", items=Immutable.List(), completed=false) {
    this.id = (+new Date() + Math.floor(Math.random() * 999999)).toString(36);
    this.title = title;
    this.items = items;
    this.completed = completed;
  }
  
}

function generateTodos() {
  
  const todos = []
  
  _.each(_.range(5), index => {
    var todo = new Todo(`Todo ${index}`);
    
    todo.completed = Math.round(Math.random()) === 0;
      
    _.each(_.range(Math.floor(Math.random()*100)), index => {
      todo.items = todo.items.push(`Item ${index}`);
    });
    
    todos.push(todo);
      
  });
  
  return todos;
}

describe('Lightning Fast Equality checks with Hash Codes', () => {
  
  it('should take separate lists with the same items and see equal hash codes', () => {

    var todos = generateTodos();
    
    let todos1 = Immutable.List.of(...todos);
    let todos2 = Immutable.List.of(...todos);

    expect(todos1).to.not.equal(todos2);
    expect(todos1.hashCode()).to.equal(todos2.hashCode());

  });
  
});

mocha.run();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值