Giter Site home page Giter Site logo

tusharf5 / runtime-memcache Goto Github PK

View Code? Open in Web Editor NEW
20.0 2.0 1.0 623 KB

runtime-memcache is a javascript key-value store for chunks of arbitrary data (strings, objects, numbers) from results of database calls, API calls, or etc. It supports many commonly used caching policies.

Home Page: https://www.npmjs.com/package/runtime-memcache

License: MIT License

JavaScript 56.56% TypeScript 43.44%
javascript nodejs browser cache runtime caching-strategies runtime-memcache typescript lru-cache mru

runtime-memcache's Introduction

javascript cache

runtime-memcache

A no dependency, high performance, near optimal javascript caching library



runtime-memcache is a caching library to store key-value cache store for small chunks of arbitrary data (strings, objects, numbers) from results of database calls, API calls, or etc. It is entirely written using Typescript and supports many commonly used caching policies.

When creating a new cache store, you can specify the policy to evict items from the store. The default policy is lru (Least Recently Used)

runtime-memcache provides flexible construction to create a cache with a combination of the following features:

  • size-based eviction when a maximum is exceeded based on frequency and recency
  • time-based expiration of entries, measured since last access or last write

Installation

npm install --save runtime-memcache
# or using yarn
yarn add runtime-memcache

Node Environment (ES6+ import/export)

import createStore from 'runtime-memcache';

Node Environment (CJS)

const createStore = require('runtime-memcache');

Browser (use as a script tag)

<script src="https://unpkg.com/[email protected]/dist/umd/index.js"></script>
<!-- OR JUST -->
<script src="https://unpkg.com/[email protected]"></script>
<script>
  // RMStore is globaly set
  const store = new RMStore();
</script>

API

Calling the createStore function returns an object with the following properties.

Property Description
get(id) Retrieves an item from the store
has(id) Check if an item exists in the store
set(id, data) Sets an item in the store
remove(id) Removes an item from the store
size() Returns the size of the item cache store
keys() Returns all the keys of the cache store as array

Config

createStore takes an optional config object as an argument with the following properties.

Property Description Type Default
timeToClear Time in milliseconds for which the store will keep an item when the policy is timeout or tlru Number 7200000
policy A Policy to evict items from the store timeout, lru, mru, tlru lru
lruSize Size of the cache store when the policy is lru or tlru Number 500
mruSize Size of the cache store when the policy is mru Number 500

Caching Policies

Following caching policies are supported.

Policy Name Description
timeout Timeout The items in the cache store will be automatically evicted after a fixed amount of time has elapsed since that item was set
lru Least Recently Used This policy evicts the least recently used items when the store size is full
tlru Time Aware Least Recently Used This policy evicts the least recently used items when the store size is full and also evict untouched items after a fixed amount of time has elapsed since that item was set
mru Most Recently Used This policy evicts the most recently used items when the store size is full

Time Complexity

Policy Method Complexity
timeout set, get, remove O(1), O(1), O(1)
lru set, get, remove O(1), O(1), O(1)
tlru set, get, remove O(1), O(1), O(1)
mru set, get, remove O(1), O(1), O(1)

Usage

Typescript

import createStore, { Config } from 'runtime-memcache';

const config: Config = {
  policy: 'lru',
  lruSize: 300, // cache a maximum of 300 users at a given time
};

interface User {
  name: string;
}

const userCache = createStore<User>(config);

async function loginUser(userId: string) {
  if (userCache.has(userId)) {
    return userCache.get(userId);
  }

  const user: User = await UserService.getUser(userId);

  userCache.set(userId, user);

  return user;
}

Javascript

import createStore from 'runtime-memcache';

const config = {
  policy: 'timeout',
  timeToClear: 7200000, // 2 hours
};

type Keys = 'key1' | 'key2';

const store = createStore(config);

store.set('key1', { name: 'name' }); // store the object and associate it with the provided key

store.get('key1'); // retrieves the object associated with this key

store.has('key1'); // returns true

store.size(); // returns 1

store.keys(); // returns ['key1']

store.remove('key1'); // deletes the object associated with this key

NPM Script Commands

  • npm run test -- Runs tests, lint and build.
  • npm run lint -- Runs ESLint.
  • npm run format -- Reformats all of the .ts and .tsx files with Prettier.
  • npm run build -- Regenerates dist folder that gets included into NPM module.

Under The Hood

runtime-memcache uses a combination of modified doubly-linked lists and hashmap data structures to achieve O(1) search-time complexity for all the methods.

Todos

  • Timeout Policy (TR)
  • Least Recently Used Policy (LRU)
  • Most Recently Used Policy (MRU)
  • Least Frequently Used Policy (LFU)
  • Time Aware Least Recently Used Policy (TLRU)
  • Random Eviction Policy (RR)
  • Add a warmup period for new items

For more information on caching policies read this

runtime-memcache's People

Contributors

tushar-gerald avatar tusharf5 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

garymatthews

runtime-memcache's Issues

set does not override existing value

Describe the bug
set method does not override value if the entry exists with given key.

To Reproduce
A simple example:

const runtimeMemcache = require("runtime-memcache")

const cache = runtimeMemcache({
  policy: 'tlru',
  lruSize: 100,
  timeToClear: 1800000
});

cache.set('key', 1)
cache.set('key', 2)

console.assert( cache.get('key') === 2 )

Expected behavior
It should override the value

Additional context
Maybe it is by design, if so it does not match the common usage, but it is not documented anywhere too or I could not find it.

Thanks for the great library.

Es6 module import does not work.

Thank you for your hard work to create this project.

I just tried to import this project with es6 module syntax:

import createStore from 'https://unpkg.com/runtime-memcache';

which results:

Uncaught SyntaxError: The requested module 'https://unpkg.com/runtime-memcache' does not provide an export named 'default'

It would be nice if we can import this project from unpkg.com link.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.