Guest User

Untitled

a guest
Feb 16th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. export default class CachedSearch {
  2. constructor(searchFunction, resultsHandler) {
  3. this.searchFunction = searchFunction;
  4. this.resultsHandler = resultsHandler;
  5.  
  6. this.query = "";
  7. this.queryCount = 0;
  8. this.cache = {};
  9. this.cacheHits = 0;
  10. this.cacheHitsHistory = [];
  11. }
  12.  
  13. changeQuery(query) {
  14. if (query.length < 3) {
  15. // noop
  16. this.resultsHandler([]);
  17. return;
  18. }
  19. if (this.cache[query]) {
  20. this.cacheHits = this.cacheHits + 1;
  21. this.queryCount = this.queryCount + 1;
  22. this.cacheHitsHistory.concat(query);
  23. console.log("query retrieved from cache:", query);
  24. this.resultsHandler(this.cache[query]);
  25. } else {
  26. this.searchFunction(query).then(results => {
  27. this.cache[query] = results;
  28. this.queryCount = this.queryCount + 1;
  29. console.log("query added to cache:", query);
  30. this.resultsHandler(results);
  31. });
  32. }
  33. }
  34. }
Add Comment
Please, Sign In to add comment