Iterator Pattern With Custom Collection

Implement a typed custom iterator for a collection with filtering and mapping lazy evaluation.

TypescriptData Fetching

Code

typescriptsnippet
1 line
export class CustomCollection<T>implements Iterable<T>{constructor(private items:T[]){}[Symbol.iterator]():Iterator<T>{let i=0;const items=this.items;return{next():IteratorResult<T>{return i<items.length?{done:false,value:items[i++]}:{done:true,value:undefined as unknown as T};}};}filter(pred:(v:T)=>boolean):CustomCollection<T>{return new CustomCollection(this.items.filter(pred));}map<U>(fn:(v:T)=>U):CustomCollection<U>{return new CustomCollection(this.items.map(fn));}toArray():T[]{return[...this.items];}}

Inside the snippet

Count the class CustomCollection as the entire surface area of Iterator Pattern With Custom Collection.

A fresh value is allocated for the result; the arguments stay untouched.

Putting it to use

CustomCollection is the public entry point; everything else in the file exists to support it.

FAQ

Does `CustomCollection` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules.