Hyperlinkv0.8.0-beta.28

Cache

Cache.invalidateWhenconsteffect/Cache.ts:955
<Key, A>(key: Key, f: Predicate<A>): <E, R>(
  self: Cache<Key, A, E, R>
) => Effect.Effect<boolean>
<Key, A, E, R>(
  self: Cache<Key, A, E, R>,
  key: Key,
  f: Predicate<A>
): Effect.Effect<boolean>

Invalidates the entry associated with the specified key in the cache when the predicate returns true for the cached value.

Example (Invalidating entries conditionally)

import { Cache, Effect } from "effect"

const program = Effect.gen(function*() {
  const cache = yield* Cache.make({
    capacity: 10,
    lookup: (key: string) => Effect.succeed(key.length)
  })

  // Add values to the cache
  yield* Cache.get(cache, "hello") // value = 5
  yield* Cache.get(cache, "hi") // value = 2

  // Invalidate when value equals 5
  const invalidated1 = yield* Cache.invalidateWhen(
    cache,
    "hello",
    (value) => value === 5
  )
  console.log(invalidated1) // true
  console.log(yield* Cache.has(cache, "hello")) // false

  // Don't invalidate when predicate doesn't match
  const invalidated2 = yield* Cache.invalidateWhen(
    cache,
    "hi",
    (value) => value === 5
  )
  console.log(invalidated2) // false
  console.log(yield* Cache.has(cache, "hi")) // true (still present)

  // Returns false for non-existent keys
  const invalidated3 = yield* Cache.invalidateWhen(
    cache,
    "nonexistent",
    () => true
  )
  console.log(invalidated3) // false

  // Returns false for failed cached values
  const cacheWithErrors = yield* Cache.make<string, number, string>({
    capacity: 10,
    lookup: (key: string) =>
      key === "fail" ? Effect.fail("error") : Effect.succeed(key.length)
  })

  yield* Effect.exit(Cache.get(cacheWithErrors, "fail"))
  const invalidated4 = yield* Cache.invalidateWhen(
    cacheWithErrors,
    "fail",
    () => true
  )
  console.log(invalidated4) // false (can't invalidate failed values)
})
combinators
Source effect/Cache.ts:95523 lines
export const invalidateWhen: {
  <Key, A>(key: Key, f: Predicate<A>): <E, R>(self: Cache<Key, A, E, R>) => Effect.Effect<boolean>
  <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, f: Predicate<A>): Effect.Effect<boolean>
} = dual(
  3,
  <Key, A, E, R>(self: Cache<Key, A, E, R>, key: Key, f: Predicate<A>): Effect.Effect<boolean> =>
    core.withFiber((fiber) => {
      const oentry = getImpl(self, key, fiber, false)
      if (oentry === undefined) {
        return effect.succeed(false)
      }
      return Deferred.await(oentry.deferred).pipe(
        effect.map((value) => {
          if (f(value)) {
            MutableHashMap.remove(self.map, key)
            return true
          }
          return false
        }),
        effect.catchCause(() => effect.succeed(false))
      )
    })
)