# Code coverage report for src/core/LRU.js

# all files / src/core/ LRU.js

67.74% Statements 21/31
50% Branches 7/14
50% Functions 3/6
67.74% Lines 21/31

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82

    1×

    30×

    30×

    30×

    1×

    1×
    28×
    28×
    28×

    28×
    28×
    28×

    1×
    64×
    64×

    36×
    36×
    36×

    36×

    1×

    1×

     import LinkedList from './LinkedList';

    /**
     * LRU Cache
     * @constructor
     * @alias clay.core.LRU
     */
    var LRU = function(maxSize) {

        this._list = new LinkedList();

        this._map = {};

        this._maxSize = maxSize || 10;
    };

    /**
     * Set cache max size
     * @param {number} size
     */
    LRU.prototype.setMaxSize = function(size) {
        this._maxSize = size;
    };

    /**
     * @param  {string} key
     * @param  {} value
     */
    LRU.prototype.put = function(key, value) {
        Eif (typeof(this._map[key]) == 'undefined') {
            var len = this._list.length();
            Iif (len >= this._maxSize && len > 0) {
                // Remove the least recently used
                var leastUsedEntry = this._list.head;
                this._list.remove(leastUsedEntry);
                delete this._map[leastUsedEntry.key];
            }

            var entry = this._list.insert(value);
            entry.key = key;
            this._map[key] = entry;
        }
    };

    /**
     * @param  {string} key
     * @return {}
     */
    LRU.prototype.get = function(key) {
        var entry = this._map[key];
        if (typeof(entry) != 'undefined') {
            // Put the latest used entry in the tail
            Eif (entry !== this._list.tail) {
                this._list.remove(entry);
                this._list.insertEntry(entry);
            }

            return entry.value;
        }
    };

    /**
     * @param {string} key
     */
    LRU.prototype.remove = function(key) {
        var entry = this._map[key];
        if (typeof(entry) != 'undefined') {
            delete this._map[key];
            this._list.remove(entry);
        }
    };

    /**
     * Clear the cache
     */
    LRU.prototype.clear = function() {
        this._list.clear();
        this._map = {};
    };

    export default LRU;