오늘도 코딩하나

[Typescript] 타입스크립트로 블록체인 만들기_Dictionary 본문

Typescript/Lecture

[Typescript] 타입스크립트로 블록체인 만들기_Dictionary

오늘도 코딩하나 2025. 1. 9. 19:10
Typescript Challenge
Dictionary

 

  • add : 새로운 단어와 그에 대한 정의를 추가한다
  • get : 입력된 단어에 대한 정의를 반환한다.
  • delete : 사전에서 특정 단어를 삭제한다.
  • update : 기존 단어의 정의를 새로운 정의로 업데이트한다.
  • showAll : 사전의 모든 단어와 정의를 출력한다.
  • count : 사전에 저장된 단어의 총 개수를 반환한다.
  • upsert : 단어가 존재하면 업데이트하고, 존재하지 않으면 추가한다.
  • exists : 특정 단어가 사전에 존재하는지 여부를 반환한다.
  • bulkAdd : 여러 단어와 정의를 한 번에 추가한다.
  • bulkDelete : 여러 단어를 한 번에 삭제한다.
type Word = { 
  term:string;
  definition:string;
}

type Words = {
  [key: string]: string;
};

class Dict {
  private words: Words;
  constructor() {
    this.words = {};
  }
  add(term: string, definition: string) {
    if (!this.get(term)) {
      this.words[term] = definition;
    }
  }
  get(term: string) {
    return this.words[term];
  }
  delete(term: string) {
    delete this.words[term];
  }
  update(term: string, newDef: string) {
    if (this.get(term)) {
      this.words[term] = newDef;
    }
  }
  showAll() {
    let output = "\n--- Dictionary Content ---\n"
    Object.keys(this.words).forEach((term) =>
      output += `${term}: ${this.words[term]}\n`
    );
    output += "--- End of Dictionary ---\n"
    console.log(output);
  }
  count() {
    return Object.keys(this.words).length;
  }
  upsert(term:string, definition:string){
    if(this.get(term)){
      this.update(term, definition);
    } else {
      this.add(term, definition);
    }
  }
  exists(term:string){
    return this.get(term) ? true : false;
  }
  bulkAdd(words: Word[]){
    words.forEach(word => this.add(word.term, word.definition))
  }
  bulkDelete(terms: string[]){
    terms.forEach(term => this.delete(term));
  }
}

const dictionary = new Dict();

const KIMCHI = "김치"


// Add
dictionary.add(KIMCHI, "밋있는 한국 음식");
dictionary.showAll();

// Count
console.log(dictionary.count());

// Update
dictionary.update(KIMCHI, "밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI));

// Delete
dictionary.delete(KIMCHI);
console.log(dictionary.count());

// Upsert
dictionary.upsert(KIMCHI, "밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI))
dictionary.upsert(KIMCHI, "진짜 밋있는 한국 음식!!!");
console.log(dictionary.get(KIMCHI))

// Exists
console.log(dictionary.exists(KIMCHI))

// Bulk Add
dictionary.bulkAdd([{term:"A", definition:"B"}, {term:"X", definition:"Y"}]);
dictionary.showAll();

// Bulk Delete
dictionary.bulkDelete(["A", "X"])
dictionary.showAll();