Skip to content

Commit

Permalink
Use mutable hashmap for rx family
Browse files Browse the repository at this point in the history
Fix #167
  • Loading branch information
jvliwanag committed Jan 6, 2025
1 parent 375a09c commit e7abb6f
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions packages/rx/src/Rx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { globalValue } from "effect/GlobalValue"
import * as Hash from "effect/Hash"
import * as Inspectable from "effect/Inspectable"
import * as Layer from "effect/Layer"
import * as MutableHashMap from "effect/MutableHashMap"
import * as Option from "effect/Option"
import { type Pipeable, pipeArguments } from "effect/Pipeable"
import * as Runtime from "effect/Runtime"
Expand Down Expand Up @@ -1025,34 +1026,35 @@ export const family = typeof WeakRef === "undefined" || typeof FinalizationRegis
<Arg, T extends object>(
f: (arg: Arg) => T
): (arg: Arg) => T => {
const atoms = new Map<number, T>()
let atoms = MutableHashMap.empty<Arg, T>()
return function(arg) {
const hash = Hash.hash(arg)
const atom = atoms.get(hash)
if (atom !== undefined) {
return atom
const atomEntry = MutableHashMap.get(atoms, arg)
if (atomEntry._tag === "Some") {
return atomEntry.value
}
const newAtom = f(arg)
atoms.set(hash, newAtom)
atoms = MutableHashMap.set(atoms, arg, newAtom)
return newAtom
}
} :
<Arg, T extends object>(
f: (arg: Arg) => T
): (arg: Arg) => T => {
const atoms = new Map<number, WeakRef<T>>()
const registry = new FinalizationRegistry<number>((hash) => {
atoms.delete(hash)
let atoms = MutableHashMap.empty<Arg, WeakRef<T>>()
const registry = new FinalizationRegistry<Arg>((arg) => {
atoms = MutableHashMap.remove(atoms, arg)
})
return function(arg) {
const hash = Hash.hash(arg)
const atom = atoms.get(hash)?.deref()
if (atom !== undefined) {
return atom
const atomEntry = MutableHashMap.get(atoms, arg).pipe(
Option.flatMapNullable((ref) => ref.deref())
);

if (atomEntry._tag === "Some") {
return atomEntry.value
}
const newAtom = f(arg)
atoms.set(hash, new WeakRef(newAtom))
registry.register(newAtom, hash)
atoms = MutableHashMap.set(atoms, arg, new WeakRef(newAtom))
registry.register(newAtom, arg)
return newAtom
}
}
Expand Down

0 comments on commit e7abb6f

Please sign in to comment.