use new ListPosition abstraction in Y.Array .slice and .get

This commit is contained in:
Kevin Jahns 2021-11-09 20:20:04 +01:00
parent 56ab251e79
commit a723c32557
3 changed files with 15 additions and 7 deletions

View File

@ -445,8 +445,8 @@ export class ListPosition {
while (item && !this.reachedEnd && (len > 0 || (len === 0 && (!item.countable || item.deleted)))) {
if (item.countable && !item.deleted && item.moved === this.currMove) {
len -= item.length
if (len <= 0) {
this.rel = -len
if (len < 0) {
this.rel = item.length + len
break
}
} else if (item.content.constructor === ContentMove) {
@ -473,6 +473,10 @@ export class ListPosition {
}
this.index -= len
this.item = item
if (len > 0) {
throw lengthExceeded
}
return this
}
/**
@ -484,7 +488,7 @@ export class ListPosition {
while (this.item && this.item.countable && !this.reachedEnd && len > 0) {
if (!this.item.deleted) {
const content = this.item.content.getContent()
const slicedContent = content.length <= len || this.rel > 0 ? content : content.slice(this.rel, len)
const slicedContent = content.length <= len && this.rel === 0 ? content : content.slice(this.rel, this.rel + len)
len -= slicedContent.length
result.push(...slicedContent)
if (content.length !== slicedContent.length) {

View File

@ -5,7 +5,6 @@
import {
YEvent,
AbstractType,
typeListGet,
typeListForEach,
typeListCreateIterator,
typeListInsertGenerics,
@ -17,7 +16,6 @@ import {
ListPosition,
ArraySearchMarker, UpdateDecoderV1, UpdateDecoderV2, UpdateEncoderV1, UpdateEncoderV2, Doc, Transaction, Item // eslint-disable-line
} from '../internals.js'
import { typeListSlice } from './AbstractType.js'
/**
* Event that describes the changes on a YArray
@ -179,7 +177,9 @@ export class YArray extends AbstractType {
* @return {T}
*/
get (index) {
return typeListGet(this, index)
return transact(/** @type {Doc} */ (this.doc), tr =>
new ListPosition(this, tr).forward(index).slice(1)[0]
)
}
/**
@ -201,7 +201,9 @@ export class YArray extends AbstractType {
* @return {Array<T>}
*/
slice (start = 0, end = this.length) {
return typeListSlice(this, start, end)
return transact(/** @type {Doc} */ (this.doc), tr =>
new ListPosition(this, tr).forward(start).slice(end < 0 ? this.length + end - start : end - start)
)
}
/**

View File

@ -456,6 +456,8 @@ const getUniqueNumber = () => _uniqueNumber++
/**
* @type {Array<function(Doc,prng.PRNG,any):void>}
*
* @todo to replace content to a separate data structure so we know that insert & returns work as expected!!!
*/
const arrayTransactions = [
function insert (user, gen) {