Skip to content

Instantly share code, notes, and snippets.

@khaled0fares
Last active September 14, 2016 11:59
Show Gist options
  • Save khaled0fares/61f32b0ba1968e3be5d2461f4b95e8c3 to your computer and use it in GitHub Desktop.
Save khaled0fares/61f32b0ba1968e3be5d2461f4b95e8c3 to your computer and use it in GitHub Desktop.
Dictionary class in es6 with text compression demo.
class Dictionary{
constructor(){
this.data = new Array();
}
add(key, val){
this.data[key] = val;
}
remove(key){
delete this.data[key]
}
get(key){
return this.data[key];
}
count(){
let keys = 0;
for(let key in this.data){
keys += 1;
}
return keys;
}
display(){
//Notice you must use for-in instead of for loop, as the length property will ignore the non numerical keys.
for(let key in this.data){
console.log(this.data[key]);
}
}
clear(){
this.data = new Array();
}
}
//====================================
class Text{
constructor(txt){
this.dic = new Dictionary();
this.indexedTxt = txt.split(" ");
}
compress(){
for(let i = 0; i < this.indexedTxt.length; i++){
let key = this.indexedTxt[i];
if(this.dic.get(key)){
this.dic.add(key, `${this.dic.get(key)},${i}`);
}else{
this.dic.add(key, `${i}`);
}
}
}
}
let txt = new Text("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.");
txt.compress();
console.log(txt.dic);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment