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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@metorial/util-memo

v2.0.0

Published

Memoization utilities for Metorial. Provides a simple and efficient memoization function for caching function results based on input parameters.

Readme

@metorial/util-memo

Memoization utilities for Metorial. Provides a simple and efficient memoization function for caching function results based on input parameters.

Installation

npm install @metorial/util-memo
# or
yarn add @metorial/util-memo
# or
pnpm add @metorial/util-memo
# or
bun add @metorial/util-memo

Features

  • 🚀 Simple Memoization: Easy-to-use memoization wrapper for any function
  • 💾 Automatic Caching: Automatically caches results based on function arguments
  • 🔍 Exact Match: Uses exact argument matching for cache lookups
  • TypeScript Support: Full TypeScript support with comprehensive type definitions
  • 🎯 Zero Dependencies: Lightweight with no external dependencies

Usage

Basic Memoization

import { memo } from '@metorial/util-memo';

// Expensive function that we want to memoize
let expensiveCalculation = (a: number, b: number) => {
  console.log('Computing...');
  return a * b + Math.sqrt(a + b);
};

// Create a memoized version
let memoizedCalculation = memo(expensiveCalculation);

// First call - computes the result
console.log(memoizedCalculation(5, 3)); // Output: Computing... 18.82842712474619

// Second call with same arguments - returns cached result
console.log(memoizedCalculation(5, 3)); // Output: 18.82842712474619 (no "Computing..." log)

// Different arguments - computes new result
console.log(memoizedCalculation(10, 2)); // Output: Computing... 22.449489742783178

API Calls with Memoization

import { memo } from '@metorial/util-memo';

// Simulate an API call
let fetchUserData = async (userId: string) => {
  console.log(`Fetching user ${userId}...`);
  // Simulate network delay
  await new Promise(resolve => setTimeout(resolve, 1000));
  return { id: userId, name: `User ${userId}`, email: `user${userId}@example.com` };
};

// Create memoized version
let memoizedFetchUser = memo(fetchUserData);

// Usage
async function getUserData() {
  // First call - makes actual API request
  let user1 = await memoizedFetchUser('123');
  console.log(user1);

  // Second call with same ID - returns cached result instantly
  let user2 = await memoizedFetchUser('123');
  console.log(user2); // Same result, no API call

  // Different ID - makes new API request
  let user3 = await memoizedFetchUser('456');
  console.log(user3);
}

Complex Object Memoization

import { memo } from '@metorial/util-memo';

interface SearchParams {
  query: string;
  filters: {
    category: string[];
    status: string;
  };
  page: number;
  limit: number;
}

let searchProducts = (params: SearchParams) => {
  console.log('Searching products with params:', params);
  // Simulate complex search logic
  return {
    results: [`Product for ${params.query}`],
    total: 100,
    page: params.page
  };
};

let memoizedSearch = memo(searchProducts);

// First search
let result1 = memoizedSearch({
  query: 'laptop',
  filters: { category: ['electronics'], status: 'active' },
  page: 1,
  limit: 10
});

// Same search - returns cached result
let result2 = memoizedSearch({
  query: 'laptop',
  filters: { category: ['electronics'], status: 'active' },
  page: 1,
  limit: 10
});

// Different search - computes new result
let result3 = memoizedSearch({
  query: 'phone',
  filters: { category: ['electronics'], status: 'active' },
  page: 1,
  limit: 10
});

React Component Optimization

import { memo } from '@metorial/util-memo';

// Expensive computation in a React component
let calculateChartData = (data: number[], options: { width: number; height: number }) => {
  console.log('Calculating chart data...');
  // Simulate expensive computation
  return data.map((value, index) => ({
    x: (index / data.length) * options.width,
    y: (value / Math.max(...data)) * options.height
  }));
};

let memoizedChartData = memo(calculateChartData);

// In your React component
function ChartComponent({ data, width, height }) {
  // This will only recalculate when data, width, or height change
  let chartData = memoizedChartData(data, { width, height });

  return (
    <svg width={width} height={height}>
      {chartData.map((point, index) => (
        <circle
          key={index}
          cx={point.x}
          cy={point.y}
          r="2"
          fill="blue"
        />
      ))}
    </svg>
  );
}

Cache Management

import { memo } from '@metorial/util-memo';

let expensiveFunction = (x: number) => {
  console.log(`Computing for ${x}`);
  return x * x + Math.sqrt(x);
};

let memoizedFn = memo(expensiveFunction);

// Cache some results
memoizedFn(1); // Caches result for [1]
memoizedFn(2); // Caches result for [2]
memoizedFn(3); // Caches result for [3]

// Access the cache (for debugging or management)
console.log(memoizedFn.cache); // Array of cached results

// Clear cache by reassigning
memoizedFn = memo(expensiveFunction);

API Reference

memo<T extends (...args: any[]) => any>(func: T)

Creates a memoized version of the provided function.

Parameters:

  • func: The function to memoize

Returns: A memoized function with the same signature as the original

Behavior:

  • Caches results based on exact argument matching
  • Returns cached result if same arguments are provided again
  • Computes and caches new result for different arguments
  • Maintains the same return type as the original function

Cache Strategy:

  • Uses an array to store cached results
  • Each cache entry contains the arguments and result
  • Performs exact matching on all arguments
  • No automatic cache expiration (cache persists for lifetime of memoized function)

License

MIT License - see LICENSE file for details.