@emotion/memoize is a simple and efficient memoization utility function that caches the results of expensive function calls based on string arguments. It provides a lightweight caching mechanism to avoid redundant calculations for functions that accept string parameters.
npm install @emotion/memoizeimport memoize from "@emotion/memoize";For CommonJS:
const memoize = require("@emotion/memoize");import memoize from "@emotion/memoize";
// Define a function that performs expensive computation
function expensiveComputation(input: string): string {
console.log(`Computing for: ${input}`);
return input.toUpperCase().repeat(3);
}
// Create a memoized version
const memoizedCompute = memoize(expensiveComputation);
// First call - computation is performed
const result1 = memoizedCompute("hello"); // Logs: "Computing for: hello"
console.log(result1); // "HELLOHELLOHELLO"
// Second call with same input - result is cached
const result2 = memoizedCompute("hello"); // No log - cached result used
console.log(result2); // "HELLOHELLOHELLO"
// Different input - computation is performed
const result3 = memoizedCompute("world"); // Logs: "Computing for: world"
console.log(result3); // "WORLDWORLDWORLD"
// Note: Each memoized function maintains its own cache throughout its lifetime
// The cache uses Object.create(null) to prevent prototype pollutionCreates a memoized version of a function that caches results based on string arguments.
/**
* Creates a memoized version of a function that caches results based on string arguments
* @param fn - Function to memoize that takes a string argument and returns a value
* @returns Memoized function with the same signature as the input function
*/
function memoize<V>(fn: (arg: string) => V): (arg: string) => V;Parameters:
fn: A function that accepts a single string argument and returns a value of type VReturns:
Type Safety:
V represents the return type of the memoized functionCaching Behavior:
Object.create(null) for the internal cache to avoid prototype pollutionUsage Examples:
// String transformation
const memoizedUpperCase = memoize((str: string) => str.toUpperCase());
console.log(memoizedUpperCase("hello")); // "HELLO"
// Complex computation returning objects
const memoizedParser = memoize((json: string) => JSON.parse(json));
const obj = memoizedParser('{"name": "John", "age": 30}');
// Function returning arrays
const memoizedSplit = memoize((str: string) => str.split(","));
const parts = memoizedSplit("a,b,c"); // ["a", "b", "c"]
// CSS processing example (common use case in emotion ecosystem)
const memoizedCSSProcessor = memoize((css: string) => {
// Expensive CSS processing logic
return css.replace(/\s+/g, " ").trim();
});The memoize function uses TypeScript generics to ensure type safety. The generic type parameter V represents the return type of the function being memoized, preserving the exact type through the memoization process. No additional types are exported by this package.