Skip to content

Commit

Permalink
fix #485 - forEach index
Browse files Browse the repository at this point in the history
  • Loading branch information
dmonad committed Jun 27, 2023
1 parent 3c98d97 commit 7ced59c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/utils/ListCursor.js
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,8 @@ export class ListCursor {
*/
forEach (tr, f) {
for (const val of this.values(tr)) {
f(val, this.index, this.type)
// decrease index because retrieving value will increase index
f(val, this.index - 1, this.type)
}
}

Expand All @@ -536,7 +537,7 @@ export class ListCursor {
const arr = new Array(this.type._length - this.index)
let i = 0
for (const val of this.values(tr)) {
arr[i++] = f(val, this.index, this.type)
arr[i++] = f(val, this.index - 1, this.type)
}
return arr
}
Expand Down
15 changes: 15 additions & 0 deletions tests/y-array.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ import * as t from 'lib0/testing'
import * as prng from 'lib0/prng'
import * as math from 'lib0/math'

/**
* foreach has correct index - see yjs#485
*
* @param {t.TestCase} tc
*/
export const testArrayIndexIssue485 = tc => {
const doc = new Y.Doc()
const yarr = doc.getArray()
yarr.push([1, 2])
yarr.forEach((el, index) => {
t.info('index: ' + index)
t.assert(yarr.get(index) === el)
})
}

/**
* @param {t.TestCase} tc
*/
Expand Down

0 comments on commit 7ced59c

Please sign in to comment.