by
82k 39
11
9
7,690
4
Top 1% !
Popular
Famous
Pearl of Wisdom
Nice
Tagged
Easy-to-find
Specified
OpenSource
Popularity: 754th place

Published on:

Frameworknode.js
Languagetypescript
libraryunderscore.js
LicenseMIT_X11

Typescript + underscore: iterating through a collection property of a class

In this example we define a signature interface (Students) to locate a student using a student ID.
In the Course class we use property getters function to provide read only access to the class members. Finally we use underscore to iterate on the Students as it was an array. 

The example runs on node.js with Typescript 0.9.5
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/33005/Typescript---underscore--iterating-throu?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
///<reference path='../types/node.d.ts'/> ///<reference path='../types/underscore.d.ts'/> import _ = require("underscore"); function write(msg) { process.stdout.write(msg+'\n'); } // Index Interface to locate a student given an id interface Students { [ studentId: number ] : Student; } class Student { private _id : number; private _name : string; private _lastName : string; constructor ( id: number, name : string, lastName : string ) { this._id = id; this._name = name; this._lastName = lastName; } // Property getters for Student get id() :number { return this._id; } get lastName() : string { return this._lastName; } } class Course { private title : string; _participants : Students = {}; constructor( t : string ) { this.title = t; } addStudent( s: Student ) { this._participants[s.id] = s; } getStudent( sid: number ) : Student { return this._participants[sid]; } // Property getter to retrieve the participants of a Course get participants() { return _.values(this._participants) } } var c = new Course("Computer Science 101"); c.addStudent(new Student(23,"Mark","Twain")); c.addStudent(new Student(100,"Albert","Einstein")); c.addStudent(new Student(120,"Isaac","Asimov")); _.each( c.participants , (s : Student) => write(s.lastName));

Other Steps and Solutions

If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus