연습문제
Dictionary 클래스를 이용해 어떤 텍스트에서 단어가 몇번 나오는지를 저장하는 프로그램을 구현하시오.
입력값(파일)
the brown fox jumped over the blue fox
출력값
the:2
brown:1
fox:2
jumped:1
over:1
blue:1
내 코드
const fs = require('fs');
function createArr(file){
var text = fs.readFileSync(file, 'utf8').split(" ");
return text;
}
var fox = createArr("fox.txt");
function Dictionary(){
this.dataStore = new Array();
}
Dictionary.prototype.add = function(key,value){
this.dataStore[key] = value;
}
Dictionary.prototype.find = function(key){
if(this.dataStore[key] == undefined){
return false;
}else{
return true;
}
}
Dictionary.prototype.remove = function(key){
delete this.dataStore[key]
}
Dictionary.prototype.showAll = function(){
for(var key in this.dataStore){
console.log(key + ":" + this.dataStore[key]);
}
}
Dictionary.prototype.count = function(){
var n = 0;
for(var key in this.dataStore){
n++;
}
return n;
}
Dictionary.prototype.clear = function(){
for(var key in this.dataStore){
delete this.dataStore[key];
}
}
Dictionary.prototype.sort = function(){
var curr = "",
toSort = [],
sorted = [];
for(let key in this.dataStore){
toSort.push(key);
}
for(let item in toSort.sort()){
sorted[toSort[item]] = this.dataStore[toSort[item]];
}
return sorted;
}
Dictionary.prototype.sort_ = function(){
d.dataStore = this.sort();
return d.dataStore;
}
function addAll(arr, dict){
for(var item in arr){
if(dict.find(arr[item])){
console.log(dict.dataStore);
dict.dataStore[arr[item]] = dict.dataStore[arr[item]] + 1;
}else{
console.log(dict.dataStore);
dict.add(arr[item],1);
}
}
}
var d = new Dictionary();
addAll(fox, d);
// d.add("c","coconut");
// d.add("b","banana");
// d.add("a","apple");
d.showAll();
// console.log(d.count());
console.log(d.find("the"));
// console.log(d.sort());
// console.log(d.dataStore);
// console.log(d.sort_());
// console.log(d.dataStore);
console.log(fox);