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));
}
}