Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/observable-map-get-or-insert.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"mobx": patch
---

Add `getOrInsert` and `getOrInsertComputed` to `ObservableMap` for compatibility with ESNext `Map` typings.
32 changes: 32 additions & 0 deletions packages/mobx/__tests__/v5/base/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,38 @@ test("issue 940, should not be possible to change maps outside strict mode", ()
}
})

test("map getOrInsert", function () {
const names = map({ user1: "User 1" })

const values = []
const dispose = autorun(() => {
values.push(names.getOrInsert("user1", "User 2"))
})
names.set("user1", "Updated")
dispose()
expect(values).toEqual(["User 1", "Updated"])

expect(names.getOrInsert("user2", "User 2")).toBe("User 2")
expect(names.get("user2")).toBe("User 2")
})

test("map getOrInsertComputed", function () {
const names = map({ user1: "User 1" })
const getName = userId => "User " + userId.slice(4)

const values = []
const dispose = autorun(() => {
values.push(names.getOrInsertComputed("user1", getName))
})
names.set("user1", "Updated")
dispose()

expect(values).toEqual(["User 1", "Updated"])

expect(names.getOrInsertComputed("user2", getName)).toBe("User 2")
expect(names.get("user2")).toBe("User 2")
})

test("issue 1243, .replace should not trigger change on unchanged values", () => {
const m = mobx.observable.map({ a: 1, b: 2, c: 3 })

Expand Down
14 changes: 14 additions & 0 deletions packages/mobx/src/types/observablemap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,20 @@ export class ObservableMap<K = any, V = any>
return this.dehanceValue_(undefined)
}

getOrInsert(key: K, value: V): V {
if (!this.has(key)) {
this.set(key, value)
}
return this.get(key)!
}

getOrInsertComputed(key: K, callback: (key: K) => V): V {
if (!this.has(key)) {
this.set(key, callback(key))
}
return this.get(key)!
}

private dehanceValue_<X extends V | undefined>(value: X): X {
if (this.dehancer !== undefined) {
return this.dehancer(value)
Expand Down