Git Product home page Git Product logo

fn-memoizer's Introduction

fn-memoizer

npm bundle size npm

A function memoizer with a LRU cache

Read more about the module at dev.to post

Install

  npm i fn-memoizer

Usage

Call memoizer with a function to memoize and optional params. All input params are JSON.strigified to create cache key.

supported options:

{
  cacheSize : 10, // defaults to 25
  expiresAt : 1000 // value in ms, defaults to null (no expiry)
}
const memoizer = require("fn-memoizer");

let count = 0;
function calc(values, multiplier, labels) {
  count++;
  const total = values.reduce((acc, x) => x + acc, 0) * multiplier;
  return `${labels.text} => ${total}`;
}
const memoizedCalc = memoizer(calc);

memoizedCalc([10, 2], 2, { text: "A" });
// count = 1

memoizedCalc([1], 1, { text: "B" });
// count = 2

memoizedCalc([10, 2], 2, { text: "A" });
// count = 2, returned cached result

Also supports asynchronous functions which return a promise.

let count = 0;
async function getTodo(id) {
  count++;
  return fetch(`https://jsonplaceholder.typicode.com/todos/${id}`).then((res) =>
    res.json()
  );
}
const memoizedGetTodo = memoizer(getTodo);

await memoizedGetTodo(1);
// count = 1

await memoizedGetTodo(2);
// count = 2

await memoizedGetTodo(1);
// count = 2

Pass cache size, also allows manual clear

let count = 0;
function add(a, b, c = 0) {
  count++;
  return a + b + c;
}
const memoAdd = memoizer(add, { cacheSize: 3 });

  memoAdd(5, 3);
  memoAdd(3, 3);
  memoAdd(1, 2);
  memoAdd(2, 4));
  // count 4
  memoAdd(1, 2);
  // count 4
  memoAdd(5, 3);
  // count 5
  // cache size is 3, hence the least used was removed
  memoAdd.clearCache();
  memoAdd(1, 2);
  // count 6
  // cache was cleared, resulting in source function getting called again

Supports expiry of cached values, accepts expiresAt value in ms

(async function () {
  let count = 0;
  function add(a, b, c = 0) {
    count++;
    return a + b + c;
  }
  const memoAdd = memoizer(add, { cacheSize: 3, expiresAt: 1000 });

  memoAdd(5, 3);
  memoAdd(3, 3);
  memoAdd(1, 2);
  memoAdd(2, 4);
  console.log(count); // 4

  await new Promise((r) => setTimeout(r, 2000));

  memoAdd(1, 2);
  console.log(count); // 5, cache expired

  memoAdd(1, 2);
  console.log(count); // 5, pulled from cache

  memoAdd(2, 4);
  console.log(count); // 6, expired value
})();

That's all folks.

fn-memoizer's People

Contributors

kailash-sankar avatar

Watchers

James Cloos avatar  avatar

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.