[Immutable.js] Exploring Sequences and Range() in Immutable.js

Understanding Immutable.js's Map() and List() structures will likely take you as far as you want to go with immutable programming. They have only small semantic differences between each other and the remaining structures in the Immutable.js family. Sequence, however, has one major difference: it's lazy--which opens a new realm of functional possibilities. Let's write a simple sequence to start.

 

Seq is lazy — Seq does as little work as necessary to respond to any method call. Values are often created during iteration, including implicit iteration when reducing or converting to a concrete data structure such as a List or JavaScript Array.

let numbers = Immutable.Range(0, 100);

let seq = Immutable.Seq.of(...numbers).take(9); // Seq do nothing now

//Use toArray() to actually make it works
console.log(seq.toArray()); // [0, 1, 2, 3, 4, 5, 6, 7, 8]

 

Cache for Seq -- You are able to use .cacheResult() method to cache the Seq:

复制代码
  it('should cache results of Seq()', () => {

    let objects = Immutable.Range(0, 1000).map(() => { return new Object(); });
    
    let take100 = objects.take(100).toArray();
    let take100Again = objects.take(100).toArray();
    
    take100.forEach((obj, index) => {
      expect(obj === take100Again[index]).to.be.false;
    })

    let cachedObjects = Immutable.Range(0, 1000).map(() => { return new Object(); }).cacheResult();

    expect(cachedObjects.size).to.equal(1000); 
    
    let take100Cached = cachedObjects.take(100).toArray();
    let take100CachedAgain = cachedObjects.take(100).toArray();
    
    take100Cached.forEach((obj, index) => {
      expect(obj === take100CachedAgain[index]).to.be.true;
    })
    
  });
复制代码

Example shows each time Seq runs will create a new objects, so if you compare 'take100' and 'take100Again', they are different object, because everytime go thoguth the Seq, it will create a new object.

But when you apply cache, the 'take100Cached' and 'take100CachedAgain' they are the same.

 

var squares = Immutable.Seq.of(1,2,3).map(x => {console.log("here");return x * x});
var res = squares.join() + squares.join();

If see the console.log(); there are six times "here";

 

var squares = Immutable.Seq.of(1,2,3).map(x => {console.log("here");return x * x}).cacheResult();
var res = squares.join() + squares.join();

When cache applies, only console.log three times.

posted @   Zhentiw  阅读(227)  评论(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工具
点击右上角即可分享
微信分享提示