Topic describes

Their thinking

If a cache is put or get, it is used once. If a cache is put or get, it is used once. If a cache is put or get, it is used once.

1: initializes the constructor

var LRUCache = function (capacity) {
    this.capacity = capacity;
    this.map = new Map(a); };Copy the code

2: Implement the GET method

  • Check whether there are target keys in the map.
    • If not, -1 is returned
    • If yes, the corresponding value is saved, then the key-value pair is deleted, saved again, and the corresponding value is returned. The reason for this re-storage is to update the first element to the oldest unused element.
LRUCache.prototype.get = function (key) {
    // If this key exists in the map, return -1
    if (this.map.has(key)) {
        const value = this.map.get(key);
        this.map.delete(key);
        this.map.set(key,value)
        return this.map.get(key);
    } else {
        return -1; }};Copy the code

3: Implements the PUT method

  • First check whether the key to be stored exists
    • Exists: Delete the file and store it again
    • If the size of the map is greater than the capacity in the constructor, delete the first element of the mapmap.entries().next().value[0]If the value is not greater than, it is stored directly.
LRUCache.prototype.put = function (key, value) {
    // If the key exists, delete it and replace it
    if (this.map.has(key)) {
        this.map.delete(key);
        this.map.set(key,value);
    } else {
        // Determine whether the map size is larger than the given capacity
        if (this.map.size >= this.capacity) {
            this.map.delete(this.map.entries().next().value[0]);
            this.map.set(key,value)
        } else {
            this.map.set(key,value)
        }
    }
};
Copy the code

The title to reflect

  • I am not familiar with the MAP API. I am not familiar with the MAP API.
  • Map.entries () becomes an iterable object.
  • Next () turns an iterable into a normal object.