0
0
Node.jsframework~10 mins

In-memory caching patterns in Node.js - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a simple in-memory cache object.

Node.js
const cache = {};

function setCache(key, value) {
  cache[[1]] = value;
}
Drag options to blanks, or click blank then click option'
Akey
Bvalue
Ccache
DsetCache
Attempts:
3 left
💡 Hint
Common Mistakes
Using the value instead of the key as the property name.
Trying to use the cache object itself as the key.
2fill in blank
medium

Complete the code to check if a key exists in the cache.

Node.js
function hasCache(key) {
  return [1] in cache;
}
Drag options to blanks, or click blank then click option'
Avalue
Bkey
Ccache
DsetCache
Attempts:
3 left
💡 Hint
Common Mistakes
Checking if the value is in the cache instead of the key.
Using the cache object on the left side of in incorrectly.
3fill in blank
hard

Fix the error in the code to retrieve a cached value safely.

Node.js
function getCache(key) {
  if (cache.[1](key)) {
    return cache[key];
  }
  return null;
}
Drag options to blanks, or click blank then click option'
Acontains
Bincludes
CindexOf
DhasOwnProperty
Attempts:
3 left
💡 Hint
Common Mistakes
Using array methods like includes or indexOf on objects.
Using non-existent methods like contains on objects.
4fill in blank
hard

Fill both blanks to implement a cache with expiration time.

Node.js
const cache = {};

function setCache(key, value, ttl) {
  cache[key] = { value: value, expiresAt: Date.now() + [1] };
}

function getCache(key) {
  const entry = cache[key];
  if (entry && entry.expiresAt > [2]) {
    return entry.value;
  }
  return null;
}
Drag options to blanks, or click blank then click option'
Attl
BDate.now()
CDate.now
DexpiresAt
Attempts:
3 left
💡 Hint
Common Mistakes
Using Date.now without parentheses, which is a function reference.
Comparing expiration with a wrong value instead of current time.
5fill in blank
hard

Fill all three blanks to implement a cache with a cleanup function that removes expired entries.

Node.js
const cache = {};

function setCache(key, value, ttl) {
  cache[key] = { value: value, expiresAt: Date.now() + [1] };
}

function cleanupCache() {
  const now = [2];
  for (const key in cache) {
    if (cache[key].expiresAt <= now) {
      [3] cache[key];
    }
  }
}
Drag options to blanks, or click blank then click option'
Attl
BDate.now()
Cdelete
Dcache
Attempts:
3 left
💡 Hint
Common Mistakes
Using Date.now without parentheses.
Trying to assign null instead of deleting the property.
Using wrong variable names in the loop.