[Javascript] Keyword 'in' to check prop exists on Object

function addTo80(n ) {
   return 80 + n;
}

function memoizedAddTo80 (fn) {
  let cache = {};
  return (n) => {
    /*keyword 'in' to check prop exists*/
    if (n in cache) {
        console.log('from cache')
        return cache[n]
    } else {
      console.log('from calculation')
      cache[n] = fn(n)
      return cache[n]
    }
  }
}

const memoAdd = memoizedAddTo80(addTo80);
memoAdd(5) // 'from calculation' 85
memoAdd(5) // 'from cache' 85
memoAdd(6) // 'from calculation' 86

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/11966743.html