All files / json-ot/types/ot-json tree.ts

87.54% Statements 232/265
68.18% Branches 60/88
81.25% Functions 26/32
87.13% Lines 210/241

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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414        5x                                     5x                 1626x 1626x 1626x 1626x 1626x 1626x               5x                   2289x 2289x 2289x 2289x 2289x 2289x               289x 289x 289x         289x           765x           765x       5x 1168x 1168x 1168x 1168x     750x       7x 7x                             5x   765x 765x 765x 765x 251x 251x   765x 387x 387x   765x 431x 431x   765x     765x 765x 765x 765x 765x     246x 246x 232x 232x 38x   52x       212x 212x 174x 174x 3x   41x       1168x 1168x 1168x       486x 486x 80x 80x 80x 80x   406x 884x 884x 884x 861x 861x 861x   884x 884x 884x 406x 405x 405x 405x 405x     884x     486x       387x 387x 387x       431x 431x 431x 38x 38x 38x 38x     393x 736x 736x 736x 712x 712x 712x   736x 736x 736x 393x 393x 393x   736x                         382x   382x 382x   382x   531x 235x 235x 235x 235x 6x 6x 6x 5x       5x 5x 5x       235x 422x 422x 3x 3x 3x 3x 2x   3x       235x 235x 212x 212x 40x 40x 40x   212x 212x 212x 41x 1x 1x 1x 1x 1x 1x     40x           382x       235x 235x 235x 211x 211x 211x 18x 18x   235x       289x 6x 6x 6x         940x 940x 327x 327x 327x 327x 327x 296x 296x 296x 296x 296x   31x 31x 8x   23x 23x 23x     327x 289x 289x 289x     940x 558x 523x 523x 523x   558x 558x         382x 382x 382x 382x 625x 380x   245x 245x 245x     382x 382x       1041x   1041x 659x                                    
import type {Expr} from '@jsonjoy.com/json-expression';
import type {Path} from '@jsonjoy.com/json-pointer';
import type {JsonOp, JsonOpDataComponent, JsonOpDropComponent, JsonOpPickComponent} from './types';
 
const toStringNode = (self: PickNode | DropNode, tab: string = ''): string => {
  let children = '';
  const last = self.children.size - 1;
  let i = 0;
  for (const [index, node] of self.children) {
    const isLast = i === last;
    children += `\n${tab}${isLast ? ' └─ ' : ' ├─ '}${node.toString(tab + (isLast ? '    ' : ' │  '))}`;
    i++;
  }
  const indexFormatted = typeof self.index === 'number' ? `[${self.index}]` : `"${self.index}"`;
  const registerFormatted =
    (self as PickNode).regId === undefined
      ? ''
      : (self as PickNode).regId === -1
        ? ''
        : ` [${(self as PickNode).regId}]`;
  return `${indexFormatted} ${self.constructor.name}${registerFormatted}${children}`;
};
 
export class PickNode {
  regId: number;
  index: number | string;
  path: Path;
  pathLength: number;
  parent: PickNode | null;
  children: Map<number | string, PickNode>;
 
  constructor(index: number | string, path: Path, pathLength: number) {
    this.regId = -1;
    this.index = index;
    this.path = path;
    this.pathLength = pathLength;
    this.parent = null;
    this.children = new Map();
  }
 
  public toString(tab: string = ''): string {
    return toStringNode(this, tab);
  }
}
 
export class DropNode {
  regId: number;
  index: number | string;
  path: Path;
  pathLength: number;
  parent: DropNode | null;
  // edits: unknown[] = [];
  children: Map<number | string, DropNode>;
 
  constructor(index: number | string, path: Path, pathLength: number) {
    this.regId = -1;
    this.index = index;
    this.path = path;
    this.pathLength = pathLength;
    this.parent = null;
    this.children = new Map();
  }
 
  public toString(tab: string = ''): string {
    return toStringNode(this, tab);
  }
 
  public clone(): DropNode {
    const clone = new DropNode(this.index, this.path, this.pathLength);
    clone.regId = this.regId;
    for (const [index, node] of this.children) {
      const child = node.clone();
      child.parent = clone;
      clone.children.set(index, child);
    }
    return clone;
  }
}
 
class PickRoot extends PickNode {
  constructor() {
    super(0, [], 0);
  }
}
 
class DropRoot extends DropNode {
  constructor() {
    super(0, [], 0);
  }
}
 
export class Register {
  public pick: PickNode | null = null;
  public data: unknown = undefined;
  public readonly drops: DropNode[] = [];
  constructor(public readonly id: number) {}
 
  addDrop(drop: DropNode) {
    this.drops.push(drop);
  }
 
  removeDrop(drop: DropNode) {
    const index = this.drops.findIndex((v) => v === drop);
    if (index > -1) this.drops.splice(index, 1);
  }
 
  toString() {
    let drops = '';
    Iif (this.drops.length)
      drops = this.drops.map((drop) => '/' + drop.path.slice(0, drop.pathLength).join('/')).join(', ');
    const src = this.pick
      ? '/' + this.pick.path.slice(0, this.pick.pathLength).join('/')
      : `{ ${JSON.stringify(this.data)} }`;
    const dst = drops ? `{ ${drops} }` : '∅';
    return `${this.id}: Register ${src} ┈┈┈→ ${dst}`;
  }
}
 
export class OpTree {
  public static from(op: JsonOp): OpTree {
    const [test, pick = [], data = [], drop = [], edit = []] = op;
    const tree = new OpTree();
    if (test.length) tree.test.push(...test);
    for (let i = 0; i < pick.length; i++) {
      const [registerId, what] = pick[i];
      tree.addPickNode(registerId, what);
    }
    for (let i = 0; i < data.length; i++) {
      const [registerId, value] = data[i];
      tree.addData(registerId, value);
    }
    for (let i = 0; i < drop.length; i++) {
      const [registerId, where] = drop[i];
      tree.addDropNode(registerId, where);
    }
    return tree;
  }
 
  protected maxRegId = -1;
  public test: Expr[] = [];
  public pick: PickNode = new PickRoot();
  public drop: DropNode = new DropRoot();
  public register = new Map<number, Register>();
 
  findPick(path: Path, pathLength: number): PickNode | undefined {
    let parent: PickNode | undefined = this.pick;
    for (let i = 0; i < pathLength; i++) {
      const index = path[i];
      if (!parent.children.has(index)) return undefined;
      parent = parent.children.get(index)!;
    }
    return parent;
  }
 
  findDrop(path: Path, pathLength: number): DropNode | undefined {
    let parent: DropNode | undefined = this.drop;
    for (let i = 0; i < pathLength; i++) {
      const index = path[i];
      if (!parent.children.has(index)) return undefined;
      parent = parent.children.get(index)!;
    }
    return parent;
  }
 
  protected setRegister(register: Register): void {
    const regId = register.id;
    if (regId > this.maxRegId) this.maxRegId = regId;
    this.register.set(regId, register);
  }
 
  addPickNode(registerId: number, what: Path, length: number = what.length): Register {
    let parent: PickNode = this.pick;
    if (!length) {
      parent.regId = registerId;
      const register = new Register(registerId);
      register.pick = parent;
      this.setRegister(register);
    } else {
      for (let i = 0; i < length; i++) {
        const index = what[i];
        const childExists = parent.children.has(index);
        if (!childExists) {
          const child = new PickNode(index, what, i + 1);
          parent.children.set(index, child);
          child.parent = parent;
        }
        const child = parent.children.get(index)!;
        const isLast = i === length - 1;
        if (isLast) {
          if (child.regId < 0) {
            child.regId = registerId;
            const register = new Register(registerId);
            register.pick = child;
            this.setRegister(register);
          }
        }
        parent = child;
      }
    }
    return this.register.get(parent.regId)!;
  }
 
  addData(registerId: number, data: unknown) {
    const register = new Register(registerId);
    register.data = data;
    this.setRegister(register);
  }
 
  addDropNode(registerId: number, where: Path) {
    let parent: DropNode = this.drop;
    const length = where.length;
    if (!length) {
      const register = this.register.get(registerId);
      if (register instanceof Register) {
        parent.regId = register.id;
        register.addDrop(parent);
      }
    } else {
      for (let i = 0; i < length; i++) {
        const index = where[i];
        const childExists = parent.children.has(index);
        if (!childExists) {
          const child = new DropNode(index, where, i + 1);
          parent.children.set(index, child);
          child.parent = parent;
        }
        const child = parent.children.get(index)!;
        const isLast = i === length - 1;
        if (isLast) {
          child.regId = registerId;
          const register = this.register.get(registerId)!;
          register.addDrop(child);
        }
        parent = child;
      }
    }
  }
 
  /**
   * Composes two operations into one combined operation. This object contains
   * the result of the composition. During the composition, both operations
   * are mutated in place, hence the `other` becomes unusable after the call.
   *
   * @param other another OpTree
   */
  public compose(other: OpTree): void {
    this.test.push(...other.test);
    // Compose deletes.
    const d1: DropNode = this.drop;
    const d2: DropNode = other.drop;
    // biome-ignore lint: using .forEach() is the fastest way to iterate over a Map
    other.register.forEach((register2) => {
      // Update pick path.
      if (register2.pick) {
        let path = register2.pick.path;
        let pathLength = register2.pick.pathLength;
        const deepestDropNodeInPath = this.findDeepestDropInPath(register2.pick.path, register2.pick.pathLength);
        if (deepestDropNodeInPath) {
          if (deepestDropNodeInPath) {
            const dropRegister = this.register.get(deepestDropNodeInPath.regId)!;
            if (dropRegister.pick) {
              path = [
                ...dropRegister.pick.path.slice(0, dropRegister.pick.pathLength),
                ...register2.pick.path.slice(0, register2.pick.pathLength).slice(deepestDropNodeInPath.pathLength),
              ];
              pathLength = path.length;
              register2.pick.path = path;
              register2.pick.pathLength = pathLength;
            }
          }
        }
        for (let i = 0; i < pathLength; i++) {
          const comp = path[i];
          if (typeof comp === 'number') {
            const pick = this.findPick(path, i);
            if (pick) {
              let numberOfPickWithLowerIndex = 0;
              pick.children.forEach((child, index) => {
                if (+index <= comp) numberOfPickWithLowerIndex++;
              });
              (path as any)[i] += numberOfPickWithLowerIndex;
            }
          }
        }
        const isDelete = !register2.drops.length;
        if (isDelete) {
          const op1Pick = this.findPick(register2.pick.path, register2.pick.pathLength);
          if (op1Pick && op1Pick.regId) {
            const register = this.register.get(op1Pick.regId);
            const alreadyDeletedInOp1 = register && !register.drops.length;
            Iif (alreadyDeletedInOp1) return;
          }
          this.addPickNode(this.maxRegId + 1, path, pathLength);
          const drop = this.findDrop(register2.pick.path, register2.pick.pathLength);
          if (drop) {
            if (drop.parent) {
              drop.parent.children.delete(drop.index);
              drop.parent = null;
              const register1 = this.register.get(drop.regId);
              if (register1 instanceof Register) {
                register1.removeDrop(drop);
                if (!register1.drops.length && !register1.pick) this.register.delete(drop.regId);
              }
            } else {
              this.drop.regId = -1;
            }
          }
        }
      }
    });
    this.composeDrops(d1, d2, other);
  }
 
  protected findDeepestDropInPath(path: Path, pathLength: number = path.length): DropNode | null {
    let longest: DropNode | null = null;
    let curr = this.drop;
    for (let i = 0; i < pathLength; i++) {
      const comp = path[i];
      const child = curr.children.get(comp);
      if (!child) break;
      curr = child;
      if (curr.regId >= 0) longest = curr;
    }
    return longest;
  }
 
  protected removeDrop(drop: DropNode): void {
    if (drop.regId >= 0) {
      const register = this.register.get(drop.regId)!;
      register.removeDrop(drop);
      if (!register.drops.length && !register.pick) this.register.delete(drop.regId);
    }
  }
 
  protected composeDrops(d1: DropNode, d2: DropNode, tree2: OpTree): void {
    const isDrop = d2.regId >= 0;
    if (isDrop) {
      const isRoot = !d2.parent;
      const clone = !isRoot ? d2.clone() : this.drop;
      const register2 = tree2.register.get(d2.regId)!;
      const isDataDrop = register2.data !== undefined;
      if (isDataDrop) {
        const newRegister = new Register(this.maxRegId + 1);
        newRegister.data = register2.data;
        newRegister.addDrop(clone);
        this.setRegister(newRegister);
        clone.regId = newRegister.id;
      } else {
        const samePickInOp1Exists = this.findPick(register2.pick!.path, register2.pick!.pathLength);
        if (samePickInOp1Exists) {
          clone.regId = samePickInOp1Exists.regId;
        } else {
          const reg = this.addPickNode(this.maxRegId + 1, register2.pick!.path, register2.pick!.pathLength);
          reg.addDrop(clone);
          clone.regId = reg.id;
        }
      }
      if (!!d1.parent && !!d2.parent) {
        const child = d1.parent.children.get(d1.index);
        if (child) this.removeDrop(child);
        d1.parent.children.set(d2.index, clone);
      }
    }
    for (const [index, child2] of d2.children) {
      if (!d1.children.has(index)) {
        const child1 = new DropNode(child2.index, child2.path, child2.pathLength);
        child1.parent = d1;
        d1.children.set(child1.index, child1);
      }
      const child1 = d1.children.get(index)!;
      this.composeDrops(child1, child2, tree2);
    }
  }
 
  public toJson(): JsonOp {
    const pick: JsonOpPickComponent[] = [];
    const data: JsonOpDataComponent[] = [];
    const drop: JsonOpDropComponent[] = [];
    for (const [index, register] of this.register) {
      if (register.data !== undefined) {
        data.push([index, register.data]);
      } else {
        const pickPath = register.pick!.path;
        const pickPathLength = register.pick!.pathLength;
        pick.push([index, pickPath.slice(0, pickPathLength)]);
      }
    }
    this.pushDropNode(drop, this.drop);
    return [this.test, pick, data, drop, []];
  }
 
  protected pushDropNode(drop: JsonOpDropComponent[], node: DropNode): void {
    if (node.regId >= 0) drop.push([node.regId, node.path.slice(0, node.pathLength)]);
    // biome-ignore lint: using .forEach() is the fastest way to iterate over a Map
    node.children.forEach((child) => {
      this.pushDropNode(drop, child);
    });
  }
 
  public toString(tab: string = ''): string {
    const picks = this.pick ? this.pick.toString(tab + '│  ') : ' ∅';
    let registers = 'Registers';
    const lastRegister = this.register.size - 1;
    let i = 0;
    for (const [id, register] of this.register) {
      const isLast = i === lastRegister;
      registers += `\n${tab}${isLast ? '│  └─' : '│  ├─'} ${register}`;
      i++;
    }
    const drops = this.drop ? this.drop.toString(tab + '   ') : ' ∅';
    return `OpTree\n${tab}├─ ${picks}\n${tab}│\n${tab}├─ ${registers}\n${tab}│\n${tab}└─ ${drops}`;
  }
}