Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Diamond kata with a TDD approach, in Javascript. Javascript noob, any feedback is most than welcome! Particularly looking for 'idiomatic' corrections.
// Diamond Kata with a TDD approach. First attempt
'use strict';
module.exports.Diamond = Diamond;
// Encapsulate line printing
function Letter(char, spaces) {
this._char = char;
this._spaces = spaces;
}
Letter.prototype.print = function print() {
return this._char + (
(this._spaces > 0)
? (Array(this._spaces + 1).join(' ') + this._char + '\n')
: '\n'
);
}
// Singleton list with all letters
var LETTERS = new function () {
// Init all upper-case letters
for (let char=65; char <= 90; char++) {
let character = String.fromCharCode(char);
this[character] = new Letter(character, (char - 65) + (char - 65 - 1));
}
}();
LETTERS.__proto__.iterateLetters = function (character, callback) {
var chars = Object.keys(this);
var last = chars.indexOf(character);
var pos = 0;
var direction = 1;
// Forwards
while (pos >= 0) {
callback(this[chars[pos]], pos, last);
if (pos === last) {
// Reached final character, return to 'A'
direction = -1;
}
pos += 1 * direction;
}
}
function Diamond (letter) {
if (typeof(letter) !== 'string' && !(letter instanceof String)) {
throw new Error('Letter must be an string');
}
this._letter = letter;
};
Diamond.prototype.process = function process() {
var prefix = function (max, current) {
return Array(1 + max - current).join(' ');
}
var result = '';
LETTERS.iterateLetters(this._letter, function (letter, current, last) {
result += prefix(last, current);
result += letter.print();
});
return result;
}
// var should = require('unit.js').should;
var should = require('should');
var diamondKata = require('../diamond_kata');
suite('Diamond', function() {
test('should be instantable', function() {
diamond = newDiamond();
diamond.should.be.an.instanceof(diamondKata.Diamond);
});
test('takes a letter as unique required parameter', function() {
(function newDiamondWithoutLetter() {newDiamond(null);})
.should.throw();
});
test('if letter is A, returns A', function() {
newDiamond('A').process().should.equal('A\n');
});
test('if letter is B, returns ABBA with proper spaces', function() {
newDiamond('B').process().should.equal(' A\nB B\n A\n');
});
test('if letter is C, returns ABBCCBBA with proper spaces', function() {
newDiamond('C').process().should.equal(' A\n B B\nC C\n B B\n A\n');
});
});
function newDiamond (letter) {
if (letter === undefined) {
letter = 'A';
}
return new diamondKata.Diamond(letter);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.