본문 바로가기

Javascript/DSA

Dictionary Data Structure

Dictionaries ?

데이터를 Key 와 Value 쌍으로 저장하는 자료구조

ADT (Abstract Data Type)

Method Name contents
add(key, value) 데이터 추가
remove(key) 데이터 삭제
has(key) 존재 여부
get(key) 데이터 호출
clear() 초기화
size() 크기
keys() 키값들
values() 데이터 값들

구현

//ES6
class Dictionary {
  constructor() {
    this.store = []
  }

  append(key, value) {
    this.store[key] = value
  }

  get(key) {
    return this.has(key) ? this.store[key] : undefined
  }

  remove(key) {
    if (this.has(key)) {
      delete this.store[key]
      return true
    }
    return false
  }

  has(key) {
    return key in this.store
  }

  clear() {
    this.store = [];
    return console.log("clear complete storage")
  }

  printValues() {
    var values = []

    for (var k in this.store) {
      if(this.has(k)) {
        values.push(this.store[k])
      }
    }
    return values
  }

  printAll() {
    return this.store;
  }

}

딕셔너리 활용

//ES6
class PhoneBook extends Dictionary {
  constructor() {
    super()
    for (let i = 0; i < 10; i += 1) {
      this.append(`USER${i}`, `010-${this.createPNum()}-${this.createPNum()}`)
    }
  }

  createPNum() {
    let checkNum = String(parseInt(Math.random() * 9999))

    if (checkNum.length == 4) {
      return checkNum
    } else {
      return this.createPNum()
    }
  }

}

var pbook = new PhoneBook()

pbook.printValues() //모든 전화번호 출력 기능
pbook.get("USER0") //특정 전화번호 출력 기능
pbook.append("jacob","010-4444-5555") //전화번호 추가
pbook.remove("USER0") //전화번호 삭제
pbook.clear() //모든 전화번호 삭제

/* exam 2*/
class sentenceDismantle extends Dictionary {
  constructor(str) {
    super()

    var regExp = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+<>@\#$%&\\\=\(\'\"]/gi
    var words = str.replace(regExp,"").split(" ");
    if (words.length <= 0) {
      console.log("please, typing the sentence.")
    } else {
      return this.wordProcessing(words);
    }

  }

  wordProcessing(words) {
    for ( let i = 0; i < words.length; i += 1) {
      if (this.has(words[i])) {
          this.append(words[i], this.get(words[i]) + 1)
        } else {
          this.append(words[i],1)
        }
    }
  }

  print() {
    return this.printAll().sort()
  }


}

'Javascript > DSA' 카테고리의 다른 글

LinkedList Data Structure  (0) 2016.08.09
Tree Data Structure (Binray Search Tree)  (0) 2016.08.09
HashTable Data Structure  (0) 2016.07.25
List Data Structure  (0) 2016.06.16
Array essential with ES6 -2-  (0) 2016.06.16