Skip to content

Instantly share code, notes, and snippets.

@dolpen
Created September 11, 2010 17:03
Show Gist options
  • Save dolpen/575361 to your computer and use it in GitHub Desktop.
Save dolpen/575361 to your computer and use it in GitHub Desktop.
<html>
<head>
<script type="text/javascript">
<!--
var ListTagNode=function(str){
this.nodeName=str||'';
this.weight=(str&&str!='')?1:0;
this.score=0;
this.distance=0;
this.childs={};
};
ListTagNode.prototype.setDistance=function(d){
this.distance=d;
}
ListTagNode.prototype.getRanking=function(){
return this.calc().slice(0,-1).sort(
function(a,b){
if(a.score!=b.score)return b.score-a.score;
return b.nodeName.length-a.nodeName.length;
}
);
};
ListTagNode.prototype.toString=function(){
var r=[];
for(var i in this.childs)r.push(this.childs[i].toString());
return this.nodeName+'='+this.score+':{\n'+r.join(',\n')+'\n}';
};
ListTagNode.prototype.calc=function(){
var r=[];
this.score=this.weight;
for(var i in this.childs){
r=r.concat(this.childs[i].calc());
this.score+=this.childs[i].score*this.distance;
}
r.push(this);
return r;
};
ListTagNode.prototype.addEntry=function(str){
if(this.nodeName==str){
this.weight++;
return;
}
if(this.childs.hasOwnProperty(str)){
this.childs[str].addEntry(str);
return;
}
for(var i in this.childs){
if(i.indexOf(str,0)==0){//p->this->i
this.childs[str] = new ListTagNode(str);
this.childs[str].setDistance(this.distance);
this.childs[str].childs.i=this.childs[i];
delete this.childs[i];
return;
}else if(str.indexOf(i,0)==0){
this.childs[i].addEntry(str);
return;
}
}
this.childs[str]=new ListTagNode(str);
this.childs[str].setDistance(this.distance);
};
window.onload=function(){
var a=new ListTagNode(),c,n=[];
a.setDistance(0.3);
a.addEntry('dwango');
a.addEntry('dolpen');
a.addEntry('dameningen');
a.addEntry('do');
a.addEntry('dream');
a.addEntry('dreamweavwer');
a.addEntry('dollor');
n=a.getRanking().slice(0,5);
for(var i=0;i<n.length;i++)alert(n[i].nodeName+'='+n[i].score);
};
//-->
</script>
</head>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment