Skip to content

Boulangerie/ts-iterable

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Iterable abstract class for TypeScript

Build Status Coveralls npm version npm downloads npm dependencies npm devDependencies npm license

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]
  }
}

With the for...of instruction

const cart = new Cart('flour', 'eggs', 'milk')
for (const article of cart) {
  console.log(article)
}

// Displays:
// "flour"
// "eggs"
// "milk"

With the Angular's ngFor directive

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.