Get Programming with JavaScript - Listing 9.10

Listing 9.10 - A Place constructor part 2

// The spacer namespace var spacer = { blank: function () { return ""; }, newLine: function () { return "\n"; }, line: function (length, character) { var longString = "****************************************"; longString += "----------------------------------------"; longString += "========================================"; longString += "++++++++++++++++++++++++++++++++++++++++"; longString += " "; length = Math.max(0, length); length = Math.min(40, length); return longString.substr(longString.indexOf(character), length); }, wrap : function (text, length, character) { var padLength = length - text.length - 3; var wrapText = character + " " + text; wrapText += spacer.line(padLength, " "); wrapText += character; return wrapText; }, box: function (text, length, character) { var boxText = spacer.newLine(); boxText += spacer.line(length, character) + spacer.newLine(); boxText += spacer.wrap(text, length, character) + spacer.newLine(); boxText += spacer.line(length, character) + spacer.newLine(); return boxText; } }; // The Place constructor var Place = function (title, description) { this.title = title; this.description = description; this.items = []; this.getItemsInfo = function () { var itemsString = "Items: " + spacer.newLine(); this.items.forEach(function (item) { itemsString += " - " + item; itemsString += spacer.newLine(); }); return itemsString; }; this.getInfo = function () { var infoString = spacer.box(this.title, this.title.length + 4, "="); infoString += this.description; infoString += spacer.newLine(); infoString += this.getItemsInfo(); infoString += spacer.line(40, "=") + spacer.newLine(); return infoString; }; this.addItem = function (item) { this.items.push(item); }; }; var library = new Place( "The Old Library", "You are in a library. Dusty books line the walls." ); library.addItem("a rusty key"); console.log(library.getInfo());

Further Adventures

Listing 9.10 - A Place constructor part 2 - Tasks 1&2

var kitchen = new Place( "The Kitchen", "You are in a kitchen. There is a disturbing smell." ); console.log(kitchen.getInfo());

Listing 9.10 - A Place constructor part 2 - Task 5

var Place = function (title, description) { this.title = title; this.description = description; this.items = []; this.getItemsInfo = function () { var itemsString = "Items: " + spacer.newLine(); this.items.forEach(function (item) { itemsString += " - " + item; itemsString += spacer.newLine(); }); return itemsString; }; this.getInfo = function () { var infoString = spacer.box(this.title, this.title.length + 4, "="); infoString += this.description; infoString += spacer.newLine(); infoString += this.getItemsInfo(); infoString += spacer.line(40, "=") + spacer.newLine(); return infoString; }; this.addItem = function (item) { this.items.push(item); }; this.removeItem = function (item) { var itemIndex = this.items.indexOf(item); this.items.splice(itemIndex, 1); }; };