std/cache/lru

Standard Library documentation

Pure ZuzuScript in-memory LRU cache.

Module

Name
std/cache/lru
Area
Standard Library
Source
modules/std/cache/lru.zzm

NAME

std/cache/lru - Pure ZuzuScript in-memory LRU cache.

SYNOPSIS

  from std/cache/lru import Cache;

  let cache := new Cache( capacity: 20 );

  let item := cache.get( "item-key", function ( item_key ) {
    # Called only on cache miss.
    return calculate_some_expensive_value( item_key );
  } );

  cache.empty();

IMPLEMENTATION SUPPORT

This module is supported by all implementations of ZuzuScript.

DESCRIPTION

This module provides a tiny in-memory least-recently-used (LRU) cache written in pure ZuzuScript.

Keys are stored in an internal Dict, and are assumed to be strings. Values may be any ZuzuScript value.

EXPORTS

Classes

  • Cache({ capacity?: Number })

    Construct a cache with a maximum number of entries. Returns: Cache. Defaults to 128.

  • cache.get(String item_key, Function producer)

    Parameters: item_key is a string key and producer is a function called on cache miss. Returns: value. Returns the cached value or stores and returns producer(item_key).

  • cache.peek(String item_key, fallback?)

    Parameters: item_key is a string key and fallback is optional. Returns: value. Returns the cached value without changing recency, or fallback/null on a miss.

  • cache.set(String item_key, value)

    Parameters: item_key is a string key and value is any value. Returns: value. Stores value and marks it as recently used.

  • cache.has(String item_key)

    Parameters: item_key is a string key. Returns: Boolean. Returns true if the cache currently contains item_key.

  • cache.size()

    Parameters: none. Returns: Number. Returns the current number of cached entries.

  • cache.capacity()

    Parameters: none. Returns: Number. Returns the configured maximum number of entries.

  • cache.empty()

    Parameters: none. Returns: null. Removes all entries from the cache.

COPYRIGHT AND LICENCE

std/cache/lru is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under the terms of either the Artistic License 1.0 or the GNU General Public License version 2.