# All files / util sorted_map.ts

91.6% Statements 218/238
90% Branches 99/110
89.47% Functions 51/57
92.07% Lines 209/227

    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
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571

    2x

    2x

    95313x

    95313x

    2x
    47348x

    2x
    15331x

    2x
    134120x
    134120x
    165245x
    165245x
    109805x
    55440x
    21532x
    33908x
    33908x

    24315x

    2x

    1862x
    1862x
    1862x
    8421x
    8421x
    1854x
    6567x
    3547x

    3020x
    3020x

    8x

    2x
    2441x

    2x
    4230x

    2x
    579x

    2x
    92x

    2x
    31193x

    2x
    4184x
    2104x
    2104x

    2x
    1x

    2x
    4129x

    2x
    4413x

    2x

    2x

    2x

    2x

    8542x
    8542x

    8542x
    8542x
    7199x

    7199x

    7199x

    574x

    574x

    6625x

    4x
    4x

    6621x
    6621x

    6621x

    2x
    6349x

    6348x
    6348x

    6348x

    6348x
    6348x
    353x
    353x

    6348x

    2x
    14467x

    2x

    2x

    2x

    2x

    2x
    2x

    310382x
    310382x

    310382x
    310382x
    310382x
    310382x

    2x

    263424x

    2x
    198873x

    2x
    32272x

    2x
    5x

    2x
    3061x
    1698x

    1363x

    2x
    579x

    2x
    143x
    92x

    51x

    2x
    70196x
    70196x
    70196x
    21558x
    48638x
    400x

    48238x

    70196x

    2x
    2202x
    1119x

    1083x
    1083x
    1083x
    1083x

    2x

    21617x
    21617x
    7392x
    2071x

    7392x

    14225x
    14225x
    2791x

    14225x
    6550x
    5431x

    1119x
    1119x

    8794x

    16186x

    2x
    378300x

    2x
    87465x
    87465x
    87465x
    87465x
    87465x

    2x
    2482x
    2482x
    511x

    511x
    511x

    2482x

    2x
    2791x
    2791x
    620x
    620x

    2791x

    2x
    20461x
    20461x

    2x
    7282x
    7282x

    2x
    21908x
    21908x
    21908x

    2x
    207x
    207x
    207x

    2x
    10244x

    10244x

    10244x
    10244x

    10244x

    2x

    2x

    2x

    2x

    9560x

    2x
    46948x

    2x
    9900x

    2x
    57570x

    2x
    63465x

    2x
    6x

    2x

    2x

    2x
    102398x

    2x

    2x
    10451x

    2x

    2x
     /**
     * Copyright 2017 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    import { assert, fail } from './assert';
    import { AnyJs } from './misc';

    /*
     * Implementation of an immutable SortedMap using a Left-leaning
     * Red-Black Tree, adapted from the implementation in Mugs
     * (http://mads379.github.com/mugs/) by Mads Hartmann Jensen
     * (mads379@gmail.com).
     *
     * Original paper on Left-leaning Red-Black Trees:
     *   http://www.cs.princeton.edu/~rs/talks/LLRB/LLRB.pdf
     *
     * Invariant 1: No red node has a red child
     * Invariant 2: Every leaf path has the same number of black nodes
     * Invariant 3: Only the left child can be red (left leaning)
     */

    export type Comparator<K> = (key1: K, key2: K) => number;

    export interface Entry<K, V> {
      key: K;
      value: V;
    }

    // An immutable sorted map implementation, based on a Left-leaning Red-Black
    // tree.
    export class SortedMap<K, V> {
      // visible for testing
      root: LLRBNode<K, V> | LLRBEmptyNode<K, V>;

      constructor(
        public comparator: Comparator<K>,
        root?: LLRBNode<K, V> | LLRBEmptyNode<K, V>
      ) {
        this.root = root ? root : LLRBNode.EMPTY;
      }

      // Returns a copy of the map, with the specified key/value added or replaced.
      insert(key: K, value: V): SortedMap<K, V> {
        return new SortedMap<K, V>(
          this.comparator,
          this.root
            .insert(key, value, this.comparator)
            .copy(null, null, LLRBNode.BLACK, null, null)
        );
      }

      // Returns a copy of the map, with the specified key removed.
      remove(key: K): SortedMap<K, V> {
        return new SortedMap<K, V>(
          this.comparator,
          this.root
            .remove(key, this.comparator)
            .copy(null, null, LLRBNode.BLACK, null, null)
        );
      }

      // Returns the value of the node with the given key, or null.
      get(key: K): V | null {
        let node = this.root;
        while (!node.isEmpty()) {
          const cmp = this.comparator(key, node.key);
          if (cmp === 0) {
            return node.value;
          } else if (cmp < 0) {
            node = node.left;
          } else Eif (cmp > 0) {
            node = node.right;
          }
        }
        return null;
      }

      // Returns the index of the element in this sorted map, or -1 if it doesn't
      // exist.
      indexOf(key: K): number {
        // Number of nodes that were pruned when descending right
        let prunedNodes = 0;
        let node = this.root;
        while (!node.isEmpty()) {
          const cmp = this.comparator(key, node.key);
          if (cmp === 0) {
            return prunedNodes + node.left.size;
          } else if (cmp < 0) {
            node = node.left;
          } else {
            // Count all nodes left of the node plus the node itself
            prunedNodes += node.left.size + 1;
            node = node.right;
          }
        }
        // Node not found
        return -1;
      }

      isEmpty(): boolean {
        return this.root.isEmpty();
      }

      // Returns the total number of nodes in the map.
      get size(): number {
        return this.root.size;
      }

      // Returns the minimum key in the map.
      minKey(): K | null {
        return this.root.minKey();
      }

      // Returns the maximum key in the map.
      maxKey(): K | null {
        return this.root.maxKey();
      }

      // Traverses the map in key order and calls the specified action function
      // for each key/value pair. If action returns true, traversal is aborted.
      // Returns the first truthy value returned by action, or the last falsey
      // value returned by action.
      inorderTraversal<T>(action: (k: K, v: V) => T): T {
        return (this.root as LLRBNode<K, V>).inorderTraversal(action);
      }

      forEach(fn: (k: K, v: V) => void) {
        this.inorderTraversal((k, v) => {
          fn(k, v);
          return false;
        });
      }

      // Traverses the map in reverse key order and calls the specified action
      // function for each key/value pair. If action returns true, traversal is
      // aborted.
      // Returns the first truthy value returned by action, or the last falsey
      // value returned by action.
      reverseTraversal<T>(action: (k: K, v: V) => T): T {
        return (this.root as LLRBNode<K, V>).reverseTraversal(action);
      }

      // Returns an iterator over the SortedMap.
      getIterator(): SortedMapIterator<K, V> {
        return new SortedMapIterator<K, V>(this.root, null, this.comparator, false);
      }

      getIteratorFrom(key: K): SortedMapIterator<K, V> {
        return new SortedMapIterator<K, V>(this.root, key, this.comparator, false);
      }

      getReverseIterator(): SortedMapIterator<K, V> {
        return new SortedMapIterator<K, V>(this.root, null, this.comparator, true);
      }

      getReverseIteratorFrom(key: K): SortedMapIterator<K, V> {
        return new SortedMapIterator<K, V>(this.root, key, this.comparator, true);
      }
    } // end SortedMap

    // An iterator over an LLRBNode.
    export class SortedMapIterator<K, V> {
      private isReverse: boolean;
      private nodeStack: Array<LLRBNode<K, V> | LLRBEmptyNode<K, V>>;

      constructor(
        node: LLRBNode<K, V> | LLRBEmptyNode<K, V>,
        startKey: K | null,
        comparator: Comparator<K>,
        isReverse: boolean
      ) {
        this.isReverse = isReverse;
        this.nodeStack = [];

        let cmp = 1;
        while (!node.isEmpty()) {
          cmp = startKey ? comparator(node.key, startKey) : 1;
          // flip the comparison if we're going in reverse
          Iif (isReverse) cmp *= -1;

          if (cmp < 0) {
            // This node is less than our start key. ignore it
            Iif (this.isReverse) {
              node = node.left;
            } else {
              node = node.right;
            }
          } else if (cmp === 0) {
            // This node is exactly equal to our start key. Push it on the stack,
            // but stop iterating;
            this.nodeStack.push(node);
            break;
          } else {
            // This node is greater than our start key, add it to the stack and move
            // to the next one
            this.nodeStack.push(node);
            Iif (this.isReverse) {
              node = node.right;
            } else {
              node = node.left;
            }
          }
        }
      }

      getNext(): Entry<K, V> {
        assert(
          this.nodeStack.length > 0,
          'getNext() called on iterator when hasNext() is false.'
        );

        let node = this.nodeStack.pop()!;
        const result = { key: node.key, value: node.value };

        Iif (this.isReverse) {
          node = node.left;
          while (!node.isEmpty()) {
            this.nodeStack.push(node);
            node = node.right;
          }
        } else {
          node = node.right;
          while (!node.isEmpty()) {
            this.nodeStack.push(node);
            node = node.left;
          }
        }

        return result;
      }

      hasNext(): boolean {
        return this.nodeStack.length > 0;
      }

      peek(): Entry<K, V> {
        if (this.nodeStack.length === 0) return null;

        const node = this.nodeStack[this.nodeStack.length - 1];
        return { key: node.key, value: node.value };
      }
    } // end SortedMapIterator

    // Represents a node in a Left-leaning Red-Black tree.
    export class LLRBNode<K, V> {
      readonly color: boolean;
      readonly left: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
      readonly right: LLRBNode<K, V> | LLRBEmptyNode<K, V>;
      readonly size: number;

      // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.
      static EMPTY: LLRBEmptyNode<any, any> = null as any;

      static RED = true;
      static BLACK = false;

      constructor(
        public key: K,
        public value: V,
        color?: boolean,
        left?: LLRBNode<K, V> | LLRBEmptyNode<K, V>,
        right?: LLRBNode<K, V> | LLRBEmptyNode<K, V>
      ) {
        this.color = color != null ? color : LLRBNode.RED;
        this.left = left != null ? left : LLRBNode.EMPTY;
        this.right = right != null ? right : LLRBNode.EMPTY;
        this.size = this.left.size + 1 + this.right.size;
      }

      // Returns a copy of the current node, optionally replacing pieces of it.
      copy(
        key: K | null,
        value: V | null,
        color: boolean | null,
        left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,
        right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null
      ): LLRBNode<K, V> {
        return new LLRBNode<K, V>(
          key != null ? key : this.key,
          value != null ? value : this.value,
          color != null ? color : this.color,
          left != null ? left : this.left,
          right != null ? right : this.right
        );
      }

      isEmpty(): boolean {
        return false;
      }

      // Traverses the tree in key order and calls the specified action function
      // for each node. If action returns true, traversal is aborted.
      // Returns the first truthy value returned by action, or the last falsey
      // value returned by action.
      inorderTraversal<T>(action: (k: K, v: V) => T): T {
        return (
          (this.left as LLRBNode<K, V>).inorderTraversal(action) ||
          action(this.key, this.value) ||
          (this.right as LLRBNode<K, V>).inorderTraversal(action)
        );
      }

      // Traverses the tree in reverse key order and calls the specified action
      // function for each node. If action returns true, traversal is aborted.
      // Returns the first truthy value returned by action, or the last falsey
      // value returned by action.
      reverseTraversal<T>(action: (k: K, v: V) => T): T {
        return (
          (this.right as LLRBNode<K, V>).reverseTraversal(action) ||
          action(this.key, this.value) ||
          (this.left as LLRBNode<K, V>).reverseTraversal(action)
        );
      }

      // Returns the minimum node in the tree.
      private min(): LLRBNode<K, V> {
        if (this.left.isEmpty()) {
          return this;
        } else {
          return (this.left as LLRBNode<K, V>).min();
        }
      }

      // Returns the maximum key in the tree.
      minKey(): K | null {
        return this.min().key;
      }

      // Returns the maximum key in the tree.
      maxKey(): K | null {
        if (this.right.isEmpty()) {
          return this.key;
        } else {
          return this.right.maxKey();
        }
      }

      // Returns new tree, with the key/value added.
      insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {
        let n: LLRBNode<K, V> = this;
        const cmp = comparator(key, n.key);
        if (cmp < 0) {
          n = n.copy(null, null, null, n.left.insert(key, value, comparator), null);
        } else if (cmp === 0) {
          n = n.copy(null, value, null, null, null);
        } else {
          n = n.copy(
            null,
            null,
            null,
            null,
            n.right.insert(key, value, comparator)
          );
        }
        return n.fixUp();
      }

      private removeMin(): LLRBNode<K, V> | LLRBEmptyNode<K, V> {
        if (this.left.isEmpty()) {
          return LLRBNode.EMPTY;
        }
        let n: LLRBNode<K, V> = this;
        if (!n.left.isRed() && !n.left.left.isRed()) n = n.moveRedLeft();
        n = n.copy(null, null, null, (n.left as LLRBNode<K, V>).removeMin(), null);
        return n.fixUp();
      }

      // Returns new tree, with the specified item removed.
      remove(
        key: K,
        comparator: Comparator<K>
      ): LLRBNode<K, V> | LLRBEmptyNode<K, V> {
        let smallest: LLRBNode<K, V>;
        let n: LLRBNode<K, V> = this;
        if (comparator(key, n.key) < 0) {
          if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) {
            n = n.moveRedLeft();
          }
          n = n.copy(null, null, null, n.left.remove(key, comparator), null);
        } else {
          if (n.left.isRed()) n = n.rotateRight();
          if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {
            n = n.moveRedRight();
          }
          if (comparator(key, n.key) === 0) {
            if (n.right.isEmpty()) {
              return LLRBNode.EMPTY;
            } else {
              smallest = (n.right as LLRBNode<K, V>).min();
              n = n.copy(
                smallest.key,
                smallest.value,
                null,
                null,
                (n.right as LLRBNode<K, V>).removeMin()
              );
            }
          }
          n = n.copy(null, null, null, null, n.right.remove(key, comparator));
        }
        return n.fixUp();
      }

      isRed(): boolean {
        return this.color;
      }

      // Returns new tree after performing any needed rotations.
      private fixUp(): LLRBNode<K, V> {
        let n: LLRBNode<K, V> = this;
        if (n.right.isRed() && !n.left.isRed()) n = n.rotateLeft();
        if (n.left.isRed() && n.left.left.isRed()) n = n.rotateRight();
        if (n.left.isRed() && n.right.isRed()) n = n.colorFlip();
        return n;
      }

      private moveRedLeft(): LLRBNode<K, V> {
        let n = this.colorFlip();
        if (n.right.left.isRed()) {
          n = n.copy(
            null,
            null,
            null,
            null,
            (n.right as LLRBNode<K, V>).rotateRight()
          );
          n = n.rotateLeft();
          n = n.colorFlip();
        }
        return n;
      }

      private moveRedRight(): LLRBNode<K, V> {
        let n = this.colorFlip();
        if (n.left.left.isRed()) {
          n = n.rotateRight();
          n = n.colorFlip();
        }
        return n;
      }

      private rotateLeft(): LLRBNode<K, V> {
        const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
        return (this.right as LLRBNode<K, V>).copy(
          null,
          null,
          this.color,
          nl,
          null
        );
      }

      private rotateRight(): LLRBNode<K, V> {
        const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
        return (this.left as LLRBNode<K, V>).copy(null, null, this.color, null, nr);
      }

      private colorFlip(): LLRBNode<K, V> {
        const left = this.left.copy(null, null, !this.left.color, null, null);
        const right = this.right.copy(null, null, !this.right.color, null, null);
        return this.copy(null, null, !this.color, left, right);
      }

      // For testing.
      checkMaxDepth(): boolean {
        const blackDepth = this.check();
        Eif (Math.pow(2.0, blackDepth) <= this.size + 1) {
          return true;
        } else {
          return false;
        }
      }

      // In a balanced RB tree, the black-depth (number of black nodes) from root to
      // leaves is equal on both sides.  This function verifies that or asserts.
      protected check(): number {
        Iif (this.isRed() && this.left.isRed()) {
          throw fail('Red node has red child(' + this.key + ',' + this.value + ')');
        }
        Iif (this.right.isRed()) {
          throw fail('Right child of (' + this.key + ',' + this.value + ') is red');
        }
        const blackDepth = (this.left as LLRBNode<K, V>).check();
        Iif (blackDepth !== (this.right as LLRBNode<K, V>).check()) {
          throw fail('Black depths differ');
        } else {
          return blackDepth + (this.isRed() ? 0 : 1);
        }
      }
    } // end LLRBNode

    // Represents an empty node (a leaf node in the Red-Black Tree).
    export class LLRBEmptyNode<K, V> {
      key: K;
      value: V;
      color: boolean;
      left: LLRBNode<K, V>;
      right: LLRBNode<K, V>;
      size = 0;

      constructor() {}

      // Returns a copy of the current node.
      copy(
        key: K | null,
        value: V | null,
        color: boolean | null,
        left: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null,
        right: LLRBNode<K, V> | LLRBEmptyNode<K, V> | null
      ): LLRBEmptyNode<K, V> {
        return this;
      }

      // Returns a copy of the tree, with the specified key/value added.
      insert(key: K, value: V, comparator: Comparator<K>): LLRBNode<K, V> {
        return new LLRBNode<K, V>(key, value);
      }

      // Returns a copy of the tree, with the specified key removed.
      remove(key: K, comparator: Comparator<K>): LLRBEmptyNode<K, V> {
        return this;
      }

      isEmpty(): boolean {
        return true;
      }

      inorderTraversal(action: (k: K, v: V) => boolean): boolean {
        return false;
      }

      reverseTraversal(action: (k: K, v: V) => boolean): boolean {
        return false;
      }

      minKey(): K | null {
        return null;
      }

      maxKey(): K | null {
        return null;
      }

      isRed(): boolean {
        return false;
      }

      // For testing.
      checkMaxDepth(): boolean {
        return true;
      }

      protected check() {
        return 0;
      }
    } // end LLRBEmptyNode

    LLRBNode.EMPTY = new LLRBEmptyNode<AnyJs, AnyJs>();