Wednesday, March 13, 2013

My solutions to programming exercises in JavaScript Step by Step 2e - Chapters 4 to 8


Even though I have already studied JavaScript in the past, I have never really done programming exercises using it. So I solved the exercises of JavaScript Step by Step 2e.

Because I am also currently learning Typescript, I solved the exercises, starting on chapter four, using both JavaScript and TypeScript.
(You can learn about TypeScript in John Papa's Blog - http://www.johnpapa.net/typescriptpost/)

You can download my solutions to chapters 4 to 8 here.



Sample code (Chapter 8 Exercise #2)
2. Create an object to hold the names of three of your favorite songs. The objects should have properties containing the artist, the song length, and the title for each song.

JavaScript:

function Song(artist, length, title) {
    this.artist = artist;
    this.length = length;
    this.title = title;
}

var songs = new Object;
songs.song1 = new Song("artist1", 101, "title1");
songs["song2"] = new Song("artist2", 102, "title2");
songs["song3"] = new Song("artist3", 103, "title3");

for (var i in songs) {
    alert(i + "=" + songs[i].title);
}

TypeScript:

class Song {
    private _title: string;

    artist: string;
    length: number;

    constructor(artist: string, length: number, title: string) {
        this.artist = artist;
        this.length = length;
        this._title = title;
    }

    get title(): string {
        return this._title;
    }

    set title(value: string) {
        if (value == undefined) throw 'value for title is undefined';
        this._title = value;
    }
}

var songs = new Object();
songs["song1"] = new Song("artist1", 101, "title1");
songs["song2"] = new Song("artist2", 102, "title2");
songs["song3"] = new Song("artist3", 103, "title3");

for (var i in songs) {
    alert(i + "=" + songs[i].title);
}