Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active June 6, 2022 21:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/8ecdda99be08ffee767f05408a560204 to your computer and use it in GitHub Desktop.
Save WebReflection/8ecdda99be08ffee767f05408a560204 to your computer and use it in GitHub Desktop.
// Least Recently Used
class LRUMap extends Map {
constructor(length) {
super().length = length;
}
_(key) {
const value = super.get(key);
super.delete(key);
super.set(key, value);
return value;
}
has(key) {
const result = super.has(key);
if (result)
this._(key);
return result;
}
get(key) {
return super.has(key) ? this._(key) : void 0;
}
set(key, value) {
super.delete(this.size < this.length ? key : super.keys().next().value);
return super.set(key, value);
}
}
@WebReflection
Copy link
Author

WebReflection commented Nov 29, 2020

Simplified version that position only on set:

// Least Recently Updated
class LRUMap extends Map {
  constructor(length) {
    super().length = length;
  }
  set(key, value) {
    super.delete(this.size < this.length ? key : super.keys().next().value);
    return super.set(key, value);
  }
}

@WebReflection
Copy link
Author

My thinking with the simplified version, is that you have length (capacity) .set(...) operations before a key goes away, without penalizing every .has(...) or .get(...) operation each time, so that the big class is always slow on .has and .get while the simplified one has slow path only on set, which is usually for new entries in the cache, while old entries could be either manually re-set, if needed, but won't impact performance on get and has.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment