Skip to content

Instantly share code, notes, and snippets.

@sys1yagi
Last active December 10, 2015 22:08
Show Gist options
  • Save sys1yagi/4499827 to your computer and use it in GitHub Desktop.
Save sys1yagi/4499827 to your computer and use it in GitHub Desktop.
Implementation of directory tree based on composoite pattern in the Typescript
//Composite Pattern
//component
interface Component{
add(child:Component):bool;
remove(child:Component):bool;
getChildren():Component[];
getName():string;
isItem():bool;
}
//leaf
class Item implements Component {
constructor(private name: string){
}
add(child:Component):bool{
throw new Error("this object is Item.");
}
remove(child:Component):bool{
throw new Error("this object is Item.");
}
getChildren():Component[]{
throw new Error("this object is Item.");
}
getName():string{
return this.name;
}
isItem():bool{
return true;
}
}
//composite
class Directory implements Component{
items:Component[];
constructor(private name: string){
this.items = new Array();
}
add(child:Component):bool{
this.items.push(child);
return true;
}
remove(child:Component):bool{
for (var i : number = this.items.length - 1; i >= 0; i--) {
if(this.items[i].getName() === child.getName()){
this.items.splice(i, 1);
i++;
}
}
return true;
}
getChildren():Component[]{
return this.items;
}
getName():string{
return this.name;
}
isItem():bool{
return false;
}
}
<html>
<html>
<head>
<script type="text/javascript" src="composite_pattern.js"></script>
<script type="text/javascript">
window.onload=function(){
var $ = function(id){return document.getElementById(id);}
//init tree
var tree = new Directory("root");
var sub_dir1 = new Directory("src");
var file_1 = new Item("Readme.txt");
var file_2 = new Item("build.xml");
var sub_dir2 = new Directory("libs");
var sub_dir3 = new Directory("bin");
tree.add(sub_dir1);
tree.add(sub_dir2);
tree.add(sub_dir3);
tree.add(file_1);
tree.add(file_2);
sub_dir1.add(new Item("Main.java"));
sub_dir1.add(new Item("Util.java"));
sub_dir1.add(new Item("Log.java"));
sub_dir2.add(new Item("library.jar"));
sub_sub_dir1 = new Directory("ext");
sub_sub_dir1.add(new Item("support.jar"));
sub_dir2.add(sub_sub_dir1);
sub_dir3.add(new Item("Main.class"));
//renderer
function renderTree(tree, padding){
var div = document.createElement("div");
div.style.paddingLeft=padding+"px";
div.innerHTML = tree.getName();
$("area").appendChild(div);
if(!tree.isItem()){
var children = tree.getChildren();
for(var i = children.length - 1; i >= 0; i--){
renderTree(children[i], padding+20);
}
}
}
renderTree(tree, 0);
}
</script>
</head>
<body>
<h3>Composite Pattern</h3>
<div id="area">
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment