Skip to content

Commit f2d2341

Browse files
authored
Use mutable hashmap for rx family (#168)
1 parent 375a09c commit f2d2341

File tree

2 files changed

+22
-16
lines changed

2 files changed

+22
-16
lines changed

.changeset/gold-ants-sing.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@effect-rx/rx": patch
3+
---
4+
5+
fix: family returning same atom if same hash

packages/rx/src/Rx.ts

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,9 @@ import * as Either from "effect/Either"
1212
import * as Exit from "effect/Exit"
1313
import { constVoid, dual, pipe } from "effect/Function"
1414
import { globalValue } from "effect/GlobalValue"
15-
import * as Hash from "effect/Hash"
1615
import * as Inspectable from "effect/Inspectable"
1716
import * as Layer from "effect/Layer"
17+
import * as MutableHashMap from "effect/MutableHashMap"
1818
import * as Option from "effect/Option"
1919
import { type Pipeable, pipeArguments } from "effect/Pipeable"
2020
import * as Runtime from "effect/Runtime"
@@ -1025,34 +1025,35 @@ export const family = typeof WeakRef === "undefined" || typeof FinalizationRegis
10251025
<Arg, T extends object>(
10261026
f: (arg: Arg) => T
10271027
): (arg: Arg) => T => {
1028-
const atoms = new Map<number, T>()
1028+
const atoms = MutableHashMap.empty<Arg, T>()
10291029
return function(arg) {
1030-
const hash = Hash.hash(arg)
1031-
const atom = atoms.get(hash)
1032-
if (atom !== undefined) {
1033-
return atom
1030+
const atomEntry = MutableHashMap.get(atoms, arg)
1031+
if (atomEntry._tag === "Some") {
1032+
return atomEntry.value
10341033
}
10351034
const newAtom = f(arg)
1036-
atoms.set(hash, newAtom)
1035+
MutableHashMap.set(atoms, arg, newAtom)
10371036
return newAtom
10381037
}
10391038
} :
10401039
<Arg, T extends object>(
10411040
f: (arg: Arg) => T
10421041
): (arg: Arg) => T => {
1043-
const atoms = new Map<number, WeakRef<T>>()
1044-
const registry = new FinalizationRegistry<number>((hash) => {
1045-
atoms.delete(hash)
1042+
const atoms = MutableHashMap.empty<Arg, WeakRef<T>>()
1043+
const registry = new FinalizationRegistry<Arg>((arg) => {
1044+
MutableHashMap.remove(atoms, arg)
10461045
})
10471046
return function(arg) {
1048-
const hash = Hash.hash(arg)
1049-
const atom = atoms.get(hash)?.deref()
1050-
if (atom !== undefined) {
1051-
return atom
1047+
const atomEntry = MutableHashMap.get(atoms, arg).pipe(
1048+
Option.flatMapNullable((ref) => ref.deref())
1049+
)
1050+
1051+
if (atomEntry._tag === "Some") {
1052+
return atomEntry.value
10521053
}
10531054
const newAtom = f(arg)
1054-
atoms.set(hash, new WeakRef(newAtom))
1055-
registry.register(newAtom, hash)
1055+
MutableHashMap.set(atoms, arg, new WeakRef(newAtom))
1056+
registry.register(newAtom, arg)
10561057
return newAtom
10571058
}
10581059
}

0 commit comments

Comments
 (0)