Skip to content
Closed
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
36 changes: 36 additions & 0 deletions __tests__/array-methods-find-mutations.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {Immer, enableArrayMethods} from "../src/immer"
import {clearPlugin, PluginArrayMethods} from "../src/internal"

for (const enabled of [false, true]) {
for (const autoFreeze of [false, true]) {
describe(`find mutations: plugin=${enabled}, autoFreeze=${autoFreeze}`, () => {
beforeEach(() => {
if (enabled) enableArrayMethods()
else clearPlugin(PluginArrayMethods)
})
afterEach(() => clearPlugin(PluginArrayMethods))

for (const method of ["find", "findLast"]) {
test(`${method} observes replacements made by its predicate`, () => {
const {produce} = new Immer({autoFreeze})
const base = [{id: 1}, {id: 2}]
const first = method === "find" ? 0 : 1
const target = 1 - first
const seen = []
const result = produce(base, draft => {
const found = draft[method]((value, index) => {
seen.push(value.id)
if (index === first) draft[target] = {id: 9}
return value.id === 9
})
expect(found).toBe(draft[target])
expect(found.id).toBe(9)
})
expect(seen).toEqual([first + 1, 9])
expect(result[target]).toEqual({id: 9})
expect(base).toEqual([{id: 1}, {id: 2}])
})
}
})
}
}
3 changes: 2 additions & 1 deletion src/plugins/arrayMethods.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,8 @@ export function enableArrayMethods() {
const start = isForward ? 0 : length - 1

for (let i = start; i >= 0 && i < length; i += step) {
if (predicate.call(thisArg, source[i], i, source)) {
const currentSource = latest(state)
if (predicate.call(thisArg, currentSource[i], i, currentSource)) {
return state.draft_[i]
}
}
Expand Down