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

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();
复制代码

 

posted @   Zhentiw  阅读(240)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示