Skip to content

Instantly share code, notes, and snippets.

@Pindar
Created February 18, 2012 10:48
Show Gist options
  • Save Pindar/1858706 to your computer and use it in GitHub Desktop.
Save Pindar/1858706 to your computer and use it in GitHub Desktop.
Prints tree of asterisks
KT.namespace("fun");
KT.fun.tree = (function () {
"use strict";
return function (height) {
var row = 1;
return (isNaN(height) || height <= 0) ? '' : new Array(height).join('.').split('.').map(function () {
return new Array(height - row + 1).join(" ") + new Array(row++ * 2).join("*");
}).join('\n');
};
})();
(function () {
var tree;
TestCase("tree", sinon.testCase({
setUp: function () {
tree = KT.fun.tree;
},
"test height one":
function () {
assertEquals("*", tree(1));
},
"test height 2":
function () {
assertEquals(" *\n***", tree(2));
},
"test height 4":
function () {
/*
*
***
*****
*******
*/
assertEquals(" *\n ***\n *****\n*******", tree(4));
}
}));
})();
<html>
<body>
<label for="rows">Please enter the number of rows: </label><input type="text" id="rows"><br/>
<div id="tree"></div>
<script>
/*jshint forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, curly:true, browser:true, devel:true, indent:4, maxerr:50, white:true */
var printTree = (function () {
"use strict";
function appendToDom(line) {
var htmlToImport = document.createElement("pre");
htmlToImport.appendChild(document.createTextNode(line));
document.getElementById('tree').appendChild(htmlToImport);
}
return function printTree(height) {
if (isNaN(height)) {
alert("Please define the height of the tree");
}
if (height < 0) {
alert("The height has to be greater then zero");
}
var row = 1;
appendToDom(new Array(height).join('.').split('.').map(function () {
return new Array(height - row + 1).join(" ") +
new Array(row++ * 2).join("*");
}).join('\n'));
};
})();
document.getElementById('rows').addEventListener("keyup", function (evt) {
"use strict";
var ENTER = 13,
DECIMAL = 10,
item;
if (evt.keyCode !== ENTER) {
return;
}
while (document.getElementsByTagName('pre')[0]) {
item = document.getElementsByTagName('pre')[0];
item.parentNode.removeChild(item);
}
printTree(parseInt(this.value, DECIMAL));
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment