2.1.1 • Published 2 years ago

@yakiyo/cache-js v2.1.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Cache JS

About

Minimal implementation of a cache using javascript's Map. Lightweight and easy to use. Includes typescript typings.

Installation

Just install the package

$ npm install @yakiyo/cache-js
# or 
$ yarn add @yakiyo/cache-js
# or
$ pnpm add @yakiyo/cache-js

Usage

Import the package in your file and initialize the class

// Es6 imports
import Cache from '@yakiyo/cache-js';

// Commonjs require
const Cache = require('@yakiyo/cache-js'); 

const cache = new Cache<k, v>(60);

The constructor takes a number which indicated the default duration in seconds upto which the cache should remain valid. You can also set duration per entry with the add method. The default is 0 if not specified while initiating.

Methods

The Cache class extends javascript's base Map class, so every method of Map can be used on instances of the cache class too.

valid(key: k): boolean

Checks if a key is valid or not based on its duration.

cache.valid('key-name'); // true or false

add(key: k, value: v, duration?: number): this

Adds a new entry to the cache. Duration is the time in seconds till which the entry should be valid. If unspecified, it uses the default duration specified while initiating the class. If even that is set to 0, the entry remains forever valid.

cache.add('key', 'value', 20); // this

addMany(...entires: Array<[K, V]>): this

Adds multiple entries to the cache. The duration is the default duration set during initialization. It takes multiple arguments, each of them being an array. The array being composed to two elements, the first one being the key, the second one being the value

cache.addMany(['k1', 'v1'], ['k2', 'v2'], ['k3', 'v3']) // this

fetch(key: k): value | undefined

Fetches a value from the cache. Returns undefined if the key doesn't exist or if the key expires. If the key expires, it is internally deleted.

cache.fetch('key'); // 'value'
cache.fetch('non-existent-key'); // undefined
cache.fetch('expired-key'); // undefined

remove(key: k): this

Removes an entry from the cache

cache.remove('key'); // this

removeMany(...keys: Array<K>): this

Removes multiple entries from the cache. It takes multiple arguments, each of them being a key, the key of the entry to remove

cache.removeMany('key 1', 'key 2', 'key 3') // this

sweep(): this

Clears all expired entries from the cache.

cache.sweep(); // cache

toArray(): Array<V>

Returns an array of all the values of cache

cache.toArray(); // ['value 1', 'value 2']

toMap(): Map<K, V>

Returns a new map of the key value pairs in the cache

cache.toMap() // [Map Object]

Side-note

This project is inspired by @discordjs/Collection

Author

Cache-js © Yakiyo. Authored and maintained by Yakiyo.

Released under MIT License

2.1.1

2 years ago

2.1.0

2 years ago

2.0.1

2 years ago

2.0.0

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago