Home
← All questions

Implement an LRU Cache for Typeahead Search Suggestions in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Cache suggestion results by query string. When the cache is full, remove the query that has gone unused the longest before storing a new…

Problem

Build a small in-memory cache for search suggestions.

TypeAheadCache(capacity) exposes fetchSuggestions(query):

  • If the query is already cached, return the stored result and treat that query as freshly used.
  • If it is missing, call the API helper, store the result, and return it.
  • When storing would push the cache past capacity, first remove the cached query that has not been used for the longest time.
class TypeAheadCache {
  constructor(capacity) {
    // Your code here
  }

  async fetchSuggestions(query) {
    // Your code here
  }

  getSuggestionsFromAPI(query) {
    return new Promise((resolve) => setTimeout(() => resolve(query), 500));
  }
}
Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium