Skip to content

Instantly share code, notes, and snippets.

@noomz
Created November 26, 2012 10:57
Show Gist options
  • Save noomz/4147635 to your computer and use it in GitHub Desktop.
Save noomz/4147635 to your computer and use it in GitHub Desktop.
Pyramid
// This require Node.js framework to complete the test case.
var pyramid = function (row, char, bg) {
if (row < 1) {
throw new Error("Row must be greater than 0.");
}
bg = bg || ' ';
var lastRowNumChar = calculateNumChar(row - 1),
numChar = 0,
padding = 0,
chars = '',
tmpChars = '',
currentRow = 0
;
for (; currentRow != row; ++currentRow) {
// Process string to print from provided char argument.
numChar = calculateNumChar(currentRow);
tmpChars = repeatChar(char, numChar);
// Then calculate padding string.
numPadding = (lastRowNumChar - numChar) / 2;
chars += padLeft(tmpChars, bg, numPadding) + "\n";
}
return chars;
// Helper functions below here.
function calculateNumChar(row) {
return 2 * row + 1;
}
function padLeft (text, paddingChar, num) {
paddingChar = paddingChar || ' ';
return repeatChar(paddingChar, num) + text;
}
function repeatChar (char, num) {
var str = '';
for (; num !== 0; --num) {
str += char;
}
return str;
}
};
var assert = require('assert');
assert.throws(function () { pyramid(0, '#'); }, Error);
assert.equal(pyramid(1, "#").replace(/\s+$/, ''), "#");
assert.equal(pyramid(2, '#').replace(/\s+$/, ''), " #\n###");
assert.equal(pyramid(3, '#').replace(/\s+$/, ''), " #\n ###\n#####");
assert.equal(pyramid(3, '#', '+').replace(/\s+$/, ''), "++#\n+###\n#####");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment