All files / json-crdt/nodes/arr ArrNode.ts

96.61% Statements 114/118
82.85% Branches 29/35
92.59% Functions 25/27
98.01% Lines 99/101

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260174x 174x 174x 174x                     174x                             75930x 75930x 75930x 75930x 75930x 75930x 75930x 75930x 75930x       23x 23x       734x 734x 734x 733x 733x 733x 733x   1x       9648x 9648x               1x                   174x         77999x     77999x                   2121x 2121x 2116x                   2121x 2121x 2116x                           32x 32x 32x 32x 32x       9759x 9759x 9671x 9671x                         440x 440x 440x 440x 427x 427x 427x 362x 362x 362x             36392x             43x                       228x       77999x   77999x   59071x 59071x 59071x 59071x 57497x 57497x 57497x 57497x 44385x 42831x 67793x 67793x 2x 2x   67791x 67791x 67791x     57497x 57497x 57497x         11262x 11262x 10254x 10254x 10023x 34362x         77999x     208x             267x 267x 267x 167x 167x     196x 196x 194x     267x       140x 84x          
import {AbstractRga, type Chunk} from '../rga/AbstractRga';
import {compare, type ITimestampStruct, tick} from '../../../json-crdt-patch/clock';
import {printBinary} from 'tree-dump/lib/printBinary';
import {printTree} from 'tree-dump/lib/printTree';
import type {Model} from '../../model';
import type {JsonNode, JsonNodeView} from '..';
import type {Printable} from 'tree-dump/lib/types';
 
type E = ITimestampStruct;
 
/**
 * @ignore
 * @category CRDT Node
 */
export class ArrChunk implements Chunk<E[]> {
  public readonly id: ITimestampStruct;
  public span: number;
  public del: boolean;
  public data: E[] | undefined;
  public len: number;
  public p: ArrChunk | undefined;
  public l: ArrChunk | undefined;
  public r: ArrChunk | undefined;
  public p2: ArrChunk | undefined;
  public l2: ArrChunk | undefined;
  public r2: ArrChunk | undefined;
  public s: ArrChunk | undefined;
 
  constructor(id: ITimestampStruct, span: number, data: E[] | undefined) {
    this.id = id;
    this.span = span;
    this.len = data ? span : 0;
    this.del = !data;
    this.p = undefined;
    this.l = undefined;
    this.r = undefined;
    this.s = undefined;
    this.data = data;
  }
 
  public merge(data: E[]) {
    this.data!.push(...data);
    this.span = this.data!.length;
  }
 
  public split(ticks: number): ArrChunk {
    const span = this.span;
    this.span = ticks;
    if (!this.del) {
      const data = this.data!;
      const rightData = data.splice(ticks);
      const chunk = new ArrChunk(tick(this.id, ticks), span - ticks, rightData);
      return chunk;
    }
    return new ArrChunk(tick(this.id, ticks), span - ticks, undefined);
  }
 
  public delete(): void {
    this.del = true;
    this.data = undefined;
  }
 
  public clone(): ArrChunk {
    return new ArrChunk(this.id, this.span, this.data ? [...this.data] : undefined);
  }
 
  public view(): E[] {
    return this.data ? [...this.data] : [];
  }
}
 
/**
 * Represents the `arr` JSON CRDT type, which is a Replicated Growable Array
 * (RGA). Each element ot the array is a reference to another JSON CRDT node.
 *
 * @category CRDT Node
 */
export class ArrNode<Element extends JsonNode = JsonNode>
  extends AbstractRga<E[]>
  implements JsonNode<JsonNodeView<Element>[]>, Printable
{
  constructor(
    public readonly doc: Model<any>,
    id: ITimestampStruct,
  ) {
    super(id);
  }
 
  /**
   * Returns a reference to an element at a given position in the array.
   *
   * @param position The position of the element to get.
   * @returns An element of the array, if any.
   */
  public get(position: number): E | undefined {
    const pair = this.findChunk(position);
    if (!pair) return undefined;
    return pair[0].data![pair[1]];
  }
 
  /**
   * Returns a JSON node at a given position in the array.
   *
   * @param position The position of the element to get.
   * @returns A JSON node, if any.
   */
  public getNode(position: number): JsonNode | undefined {
    const id = this.get(position);
    if (!id) return undefined;
    return this.doc.index.get(id);
  }
 
  /**
   * Returns ID of the RGA slot (not the referenced JSON node) at a given position
   * in the array. The ID is a timestamp the unique slot of the element in the RGA.
   * To retrieve the JSON node ID referenced by the slot, use {@link get} method.
   *
   * @todo Rename to `getRef`.
   *
   * @param position The position of the element to get.
   * @returns ID of the RGA slot.
   */
  public getId(position: number): ITimestampStruct | undefined {
    const pair = this.findChunk(position);
    Iif (!pair) return undefined;
    const [chunk, offset] = pair;
    const id = chunk.id;
    return !offset ? id : tick(id, offset);
  }
 
  public getById(id: ITimestampStruct): E | undefined {
    const chunk = this.findById(id);
    if (!chunk || chunk.del) return undefined;
    const offset = id.time - chunk.id.time;
    return chunk.data![offset];
  }
 
  /**
   * Updates an array element in-place. Used by the "upd_arr" operation.
   *
   * @todo Verify that the new ID is greater than the old ID.
   *
   * @param ref A reference to the element slot in the array.
   * @param val A new value to set in the slot.
   * @returns The old value of the slot, if any.
   */
  public upd(ref: ITimestampStruct, val: ITimestampStruct): ITimestampStruct | undefined {
    const chunk = this.findById(ref);
    Iif (!chunk) return;
    const data = chunk.data;
    if (!data) return;
    const offset = ref.time - chunk.id.time;
    const currentVal = data[offset];
    if (currentVal && compare(currentVal, val) >= 0) return;
    data[offset] = val;
    this.onChange();
    return currentVal;
  }
 
  // -------------------------------------------------------------- AbstractRga
 
  /** @ignore */
  public createChunk(id: ITimestampStruct, data: E[] | undefined): ArrChunk {
    return new ArrChunk(id, data ? data.length : 0, data);
  }
 
  /** @ignore */
  protected onChange(): void {}
 
  protected toStringName(): string {
    return this.name();
  }
 
  // ----------------------------------------------------------------- JsonNode
 
  /** @ignore */
  public child() {
    return undefined;
  }
 
  /** @ignore */
  public container(): JsonNode | undefined {
    return this;
  }
 
  /** @ignore */
  private _tick: number = 0;
  /** @ignore */
  private _view: unknown[] = [];
  public view(): JsonNodeView<Element>[] {
    const doc = this.doc;
    const tick = doc.clock.time + doc.tick;
    const _view = this._view;
    if (this._tick === tick) return _view as JsonNodeView<Element>[];
    const view = [] as unknown[];
    const index = doc.index;
    let useCache = true;
    for (let chunk = this.first(); chunk; chunk = this.next(chunk)) {
      if (chunk.del) continue;
      for (const node of chunk.data!) {
        const elementNode = index.get(node);
        if (!elementNode) {
          useCache = false;
          continue;
        }
        const element = elementNode.view() as JsonNodeView<Element>;
        if (_view[view.length] !== element) useCache = false;
        view.push(element);
      }
    }
    if (_view.length !== view.length) useCache = false;
    const result = useCache ? _view : ((this._tick = tick), (this._view = view));
    return result as JsonNodeView<Element>[];
  }
 
  /** @ignore */
  public children(callback: (node: JsonNode) => void) {
    const index = this.doc.index;
    for (let chunk = this.first(); chunk; chunk = this.next(chunk)) {
      const data = chunk.data;
      if (!data) continue;
      const length = data.length;
      for (let i = 0; i < length; i++) callback(index.get(data[i])!);
    }
  }
 
  /** @ignore */
  public api: undefined | unknown = undefined;
 
  public name(): string {
    return 'arr';
  }
 
  // ---------------------------------------------------------------- Printable
 
  /** @ignore */
  protected printChunk(tab: string, chunk: ArrChunk): string {
    const pos = this.pos(chunk);
    let valueTree = '';
    if (!chunk.del) {
      const index = this.doc.index;
      valueTree = printTree(
        tab,
        chunk
          .data!.map((id) => index.get(id))
          .filter((node) => !!node)
          .map((node, i) => (tab) => `[${pos + i}]: ${node!.toString(tab + '    ' + ' '.repeat(String(i).length))}`),
      );
    }
    return (
      this.formatChunk(chunk) +
      valueTree +
      printBinary(tab, [
        chunk.l ? (tab) => this.printChunk(tab, chunk.l!) : null,
        chunk.r ? (tab) => this.printChunk(tab, chunk.r!) : null,
      ])
    );
  }
}