npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@omni-tools/mem

v6.0.0-alpha.4

Published

Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input

Downloads

14

Readme

Mem

Npm Version Build Status codecov

(Memory Expirable Memoize) :floppy_disk:

Memoize functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input

Memory is automatically released when an item expires.

:loudspeaker: This is a fork of @Sindresorhus mem package. It adds possibility to have non static max age, and a extend max age on access. (with a throttle mecanism)

So far its still kind of experiment, but It might end up to be merged :slightly_smiling_face:

Install

$ npm install @omni-tools/mem

Usage

const mem = require('@omni-tools/mem');

let i = 0;
const counter = () => ++i;
const memoized = mem(counter);

memoized('foo'); //=> 1

// Cached as it's the same arguments
memoized('foo'); //=> 1

// Not cached anymore as the arguments changed
memoized('bar'); //=> 2

memoized('bar'); //=> 2
Works fine with promise returning functions
const mem = require('@omni-tools/mem');

let i = 0;
const counter = async () => ++i;
const memoized = mem(counter);

(async () => {
	console.log(await memoized()); //=> 1

	// The return value didn't increase as it's cached
	console.log(await memoized()); //=> 1
})();
const mem = require('@omni-tools/mem');
const got = require('got');
const delay = require('delay');

const memGot = mem(got, {maxAge: 1000});

(async () => {
	await memGot('sindresorhus.com');

	// This call is cached
	await memGot('sindresorhus.com');

	await delay(2000);

	// This call is not cached as the cache has expired
	await memGot('sindresorhus.com');
})();

API

mem(fn, options?)

  • fn: Function to be memoized. (Type: Function)
  • options: Diverses option to customize memoizing behavior (_Type: object, default: {} _) you'll find bellow the different available options
maxAge

Configuration for the maxAge configuration mecanism

Originaly just the Milliseconds until the cache expires.

  • Type: (number|function|object)
  • Default: Infinity

More complex options can be now used, as you can now provide as maxAge:

  • a function: this one will be injected the key and should return the moment(timestamp) at which the item should expire
  • an object: this one is necessary to configure the refresh mecanism on acess
    • ttl: the ttl attached to new item. (this is the equivalent for simple number maxAge)
    • expirationDate: function to compute the expiration data for new item with given key (value returned by cacheKey function)
    • extendOnAccess: increment to be added to maxAge of item being accessed (Type: number)
    • setOnAccess: Function that will determine the new maxAge for the object being accessed. (Type: (key:string, currentMaxAge:number) => future_max_age:numver)
    • extensionThrottle: throttle the extension of maxAge of the object being accessed (Type: number|boolean) if value is true, default throttle value of 1 second will be applied. if some number is given, any access to the item will not cause a maxAge extension until the end of this cooldown (in millisecond)
cacheKey

Determines the cache key for storing the result based on the function arguments.

  • Type: Function

By default, if there's only one argument and it's a primitive, it's used directly as a key (if it's a function, its reference will be used as key), otherwise it's all the function arguments JSON stringified as an array.

You could for example change it to only cache on the first argument x => JSON.stringify(x).

cache

Specify the cache object to use

  • Type: object
  • Default: new Map()

Use a different cache storage. Must implement the following methods: .has(key), .get(key), .set(key, value), .delete(key), and optionally .clear(). You could for example use a WeakMap instead or quick-lru for a LRU cache.

cachePromiseRejection

Cache rejected promises.

  • Type: boolean
  • Default: true

mem.clear(fn)

Clear all cached data of a memoized function.

  • fn : Some Memoized function.(Type: Function)

Tips

Cache statistics

If you want to know how many times your cache had a hit or a miss, you can make use of stats-map as a replacement for the default cache.

Example

const mem = require('@omni-tools/mem');
const StatsMap = require('stats-map');
const got = require('got');

const cache = new StatsMap();
const memGot = mem(got, {cache});

(async () => {
	await memGot('sindresorhus.com');
	await memGot('sindresorhus.com');
	await memGot('sindresorhus.com');

	console.log(cache.stats); //=> {hits: 2, misses: 1}
})();

Related

  • p-memoize - Memoize promise-returning & async functions