Iterable abstract class for TypeScript
Make any object iterable with the Typescript Iterable abstract class. The iterable class uses the standard Symbol.iterator symbol for iteration.
Install
The easiest way is to install ts-iterable
as dependency
:
npm install ts-iterable --save
Usage
Extending the Iterable abstract class
class Cart extends Iterable {
private articles: string[]
public constructor(...articles) {
super()
this.articles = articles
}
public valid(key): boolean {
return key < this.articles.length
}
public current(key): any {
return this.articles[key]
}
}
for...of
instruction
With the const cart = new Cart('flour', 'eggs', 'milk')
for (const article of cart) {
console.log(article)
}
// Displays:
// "flour"
// "eggs"
// "milk"
ngFor
directive
With the Angular's cart.component.ts
@Component({
selector: 'app-cart',
templateUrl: './cart.component.html'
})
export class CartComponent {
public cart: Cart
public constructor() {
this.cart = new Cart('flour', 'eggs', 'milk')
}
cart.component.html
<h1>Your cart</h1>
<ul>
<li *ngFor="let article of cart">{{article}}</li>
</ul>
License
Code licensed under MIT License.