class를 사용하여 단어장을 만들었다.
//list를 담아줄 type지정
type List = {
[key:string]:string
}
//단어 속성과 타입 지정
class Word{
constructor(
public readonly tit:string,
public readonly des:string
){}
}
//단어장 만들기 시작
class Dict{
//Dict클래스를 참조했을때만 사용할 수 있게 protected사용
//class내부의 list는 type List참조
protected list:List
constructor(){
//list 초기화
this.list = {}
}
// 단어를 추가
add(item:Word){
return this.list[item.tit] === undefined && (this.list[item.tit] = item.des)
}
//단어의 정의를 리턴
getWord(item:string){
return this.list[item]
}
//단어를 삭제
del(item:string){
return this.list[item] !== undefined && delete this.list[item]
}
//단어를 업데이트
update(itemOld:string,itemNew:string){
if(this.list.hasOwnProperty(itemOld)){
this.list[itemNew] = this.list[itemOld]
delete this.list[itemOld]
}
return
}
//사전 단어를 모두 보여줌
showAll(){
return Object.keys(this.list)
}
//사전 단어들의 총 갯수를 리턴
count():number{
return Object.keys(this.list).length
}
//단어를 업데이트, 존재하지 않을시 추가
upsert(item:string,item2:string){
return this.list[item] === undefined ? (this.list[item2] = "person") : this.update(item,item2)
}
//단어가 사전에 존재하는지 여부
exists(item:string){
return this.list[item] === undefined ? false : true
}
//여러개의 단어를 한번에 추가
bulkAdd(item:Word[]){
for(const i of item){
this.list.tit !== i.tit && (this.list[i.tit] = i.des)
}
}
//여러개의 단어를 한번에 삭제
bulkDelete(item:string[]){
item.map(i => {
this.list.tit !== i && (delete this.list[i])
})
}
}
const addWord = new Dict
const kim = new Word("kim","person")
addWord.add(kim)
addWord.getWord("kim")
// addWord.del("kim")
addWord.showAll()
addWord.bulkAdd([{tit:"lee",des:"person"},{tit:"hong",des:"person"},{tit:"choi",des:"person"}])
// addWord.bulkDelete(["lee","hong"])
addWord.exists("kim")
// addWord.update("lee","kang")
addWord.upsert("kim","lala")
console.log('addWord', addWord);
class를 사용하여 여러 함수 메소드를 만들어서 사용하니 되게 편했다.
오랜만에 여러 계산식을 만들다보니 머리가 지끈 거렸지만 다시금 개발의 뇌로 돌아가는거 같아서 다양한 계산식을 연습해봐야겠다.