The type of keys in the Map
The type of values in the Map
The existing value if found, or the newly created value
// Simple caching example
const userCache = new Map<number, User>();
const user = MapUtil.take(userCache, userId, () => {
// This expensive operation only runs if userId is not cached
return fetchUserFromDatabase(userId);
});
// Configuration object caching
const configs = new Map<string, Config>();
const dbConfig = MapUtil.take(configs, "database", () => ({
host: "localhost",
port: 5432,
database: "myapp",
}));
// Lazy computation results
const computationCache = new Map<string, number>();
const result = MapUtil.take(computationCache, "fibonacci-40", () => {
console.log("Computing fibonacci(40)...");
return fibonacci(40); // Only computed once
});
// Using with complex keys
const cache = new Map<[number, number], Matrix>();
const key: [number, number] = [rows, cols];
const matrix = MapUtil.take(cache, key, () =>
generateIdentityMatrix(rows, cols),
);
contracts/common.md#principled-implementation The key is looked up with has, so an existing value, even undefined, is returned without calling the factory; otherwise the factory is called once, its value is stored, and the same value is returned.
contracts/common.md#clear-and-simple-design A single check, one factory call, and one store.
Retrieves a value from a Map or creates it using a lazy initialization function.
This function implements the "get or create" pattern for Maps. If the key exists in the Map, it returns the existing value. Otherwise, it calls the provided factory function to create a new value, stores it in the Map, and returns it. The factory function is only called when the key doesn't exist, enabling lazy initialization and caching patterns.
Processing cost: One membership test and lookup, or one factory invocation and insertion, avoid a map scan; native Map access is sublinear on average and factory cost belongs to the supplied computation.
Reuse: Stored values, including promises and undefined, are reused while the supplied Map retains the key. The caller must key every relevant dependency and remove stale or rejected entries; this helper cannot establish external-data freshness or prevent reentrant factory calls.
Resource ownership: New values are transferred into the caller-owned Map, whose growth and eviction remain the caller responsibility; the helper acquires no external handle or background task.