mituri

[JS] proxy pattern

Jul 22nd, 2020 (edited)
2,388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class CryptocurrencyAPI {
  2.   getValue(coin) {
  3.     console.log("Calling external API...")
  4.    
  5.     switch(coin) {
  6.       case "bitcoin": return "$2";
  7.       case "littlecoin": return "$6";
  8.       case "ethernum": return "$9";
  9.     }
  10.   }
  11. }
  12.  
  13. class cryptocurrencyProxy {
  14.     constructor() {
  15.     this.api = new CryptocurrencyAPI()
  16.     this.cache = {}
  17.   }
  18.  
  19.   getValue(coin) {
  20.     if (this.cache[coin] == null) {
  21.       this.cache[coin] = this.api.getValue(coin)
  22.     }
  23.     return this.cache[coin]
  24.   }
  25. }
  26.  
  27. const proxy = new cryptocurrencyProxy()
  28.  
  29. console.log(proxy.getValue("bitcoin"))
  30. console.log(proxy.getValue("littlecoin"))
  31. console.log(proxy.getValue("ethernum"))
  32. console.log(proxy.getValue("bitcoin"))
  33. console.log(proxy.getValue("bitcoin"))
  34. console.log(proxy.getValue("ethernum"))
Add Comment
Please, Sign In to add comment