Documentation
    Preparing search index...
    • 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.

      Type Parameters

      • K

        The type of keys in the Map

      • V

        The type of values in the Map

      Parameters

      • map: Map<K, V>

        The Map to retrieve from or update

      • key: K

        The key to look up in the Map

      • value: () => V

        A factory function that creates the value if key doesn't exist

      Returns V

      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)
      );