diff --git a/src/utils/ListCursor.js b/src/utils/ListCursor.js index 010243a2..17e47652 100644 --- a/src/utils/ListCursor.js +++ b/src/utils/ListCursor.js @@ -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) } } @@ -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 } diff --git a/tests/y-array.tests.js b/tests/y-array.tests.js index e8cb644e..b1f619bd 100644 --- a/tests/y-array.tests.js +++ b/tests/y-array.tests.js @@ -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 */