All files / src/resp/data sorted-set.ts

90.65% Statements 359/396
85.54% Branches 219/256
91.42% Functions 32/35
90.56% Lines 355/392

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 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 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 10191x                                   538x 538x 538x         3421x                   1x   4x             4x     4x 11x     11x   4x     4x 2x         2x 1x                       1x 1x 4x   1x 2x 2x 2x 21x 5x 5x     2x       1x 1x 11x 2x     1x       2x 2x 2x 22x   2x 22x 14x     2x       1x 1x 1x 10x   1x 11x 7x     1x 11x 4x     1x     91x   91x           91x           91x           91x         91x 91x                                                                       270x 2x     268x   268x 9x 3x   6x           265x       265x 4x         4x       261x 261x                                 2x 2x                         10x 1x     9x 1x   9x 3x     9x 1x     8x 2x       6x 6x   6x       6x 14x 15x 15x         6x         2x       94x 94x 94x 94x         94x   94x   3008x                 3x       7x                                         2x   2x 1x       1x     1x       1x       7x 1x       6x 6x   6x 14x 14x     6x                                   17x 1x     16x 1x 15x 5x           16x 6x 10x 4x     16x 1x     15x 1x     15x 12x         15x 15x 15x 15x                   15x       15x 3x 6x       6x     12x 40x 40x       15x                         20x 20x   20x 1x     19x 15x         19x 6x   19x 10x     19x 8x     11x 2x     9x 9x   9x 3x 9x 9x   9x     9x 9x             6x 32x 32x   32x     32x 32x         9x                           11x   11x 3x       8x 8x 8x   8x 16x 18x 18x   16x 8x                               16x 16x 12x       12x 12x   4x                             2x   2x       2x   2x             2x   2x       2x     2x       2x 1x 1x     1x 1x     1x   1x 4x 1x 1x   4x     1x 1x 1x   1x 5x 5x       5x 5x 5x 5x     1x 1x                     2x   2x       2x     2x       2x 1x 1x 1x         1x 1x   1x 2x 1x   2x   1x   1x 5x 5x       5x 5x 5x     1x 1x                 12x 12x             1x                     1x 1x   1x                                 28x 4x     24x 10x           24x 24x   24x 7x 32x       32x     17x 110x 110x       24x           1x         1x 1x   1x 3x 3x     1x         15x   15x       15x   15x 54x 19x       15x                     3x 3x   3x 7x 9x 9x   7x 3x             266x                   266x 266x 266x 266x     266x 626x       626x 626x 394x 30x 4x   26x 3x     387x 387x     622x     622x     262x       262x 262x   45x 76x 76x 76x   45x     262x         262x 413x       413x 413x     262x 281x     262x     262x 160x   102x     262x 262x         18x 18x       18x 54x 18x   54x     18x   18x         18x       18x         28x 28x 28x   28x 82x 41x 41x   41x     28x 28x 24x   4x     28x 7x         262x 262x 151x   262x          
import * as assert from "assert";
import * as util from "util";
 
/*
 * A rewrite of https://www.npmjs.com/package/redis-sorted-set
 * tslint:disable:no-conditional-assignment
 * tslint:disable:max-classes-per-file
 */
 
/*
 * Value is score, sorted
 * key is obj, unique
 */
class Node {
  public next: any[];
 
  public prev: any;
 
  constructor(public level: number, public key: any, public value: number) {
      this.next = new Array(this.level);
      this.prev = null;
  }
}
 
class Level {
    constructor(public next: Node, public span: number) {
    }
}
 
/**
 * A Typescript implementation of [redis-sorted-set](https://www.npmjs.com/package/redis-sorted-set)
 *
 * Largely unchanged
 *
 */
export class SortedSet implements Iterable<SortedSet> {
    public static intersect(...nodes: any[]): Node[] {
        let result: Node[] = [],
            node: Node,
            lookup: any,
            x: number,
            i: number,
            j: number,
            n: number;
        Iif (!nodes.length) {
            return [];
        }
        for (i = nodes.length - 1; i >= 0; i--) {
            Iif (!nodes[i].length) { // Abort
                return [];
            }
            nodes[i] = nodes[i]._head.next[0].next;
        }
        Iif (nodes.length === 1) {
            return nodes[0].toArray({"field": "key"});
        }
        if (nodes.length === 2) {
            return SortedSet.binaryIntersect(
                nodes[0],
                nodes[1]
            );
        }
        if (nodes.length === 3) {
            return SortedSet.ternaryIntersect(
                nodes[0],
                nodes[1],
                nodes[2]
            );
        }
 
        /*
         *Return nodes[0].length <= nodes[1].length ?
         *binaryIntersect(nodes[0], nodes[1]) :
         *binaryIntersect(nodes[1], nodes[0]);
         */
        lookup = Object.create(null);
        for (node = nodes.shift(); node; node = node.next[0].next) {
            lookup[node.key] = 0;
        }
        for (i = 0, n = nodes.length - 1; i < n; i++) {
            x = 0;
            j = i + 1;
            for (node = nodes[i]; node; node = node.next[0].next) {
                if (lookup[node.key] === i) {
                    lookup[node.key] = j;
                    x++;
                }
            }
            Iif (!x) { // Useful?
                return [];
            }
        }
        result = [];
        for (node = nodes[i]; node; node = node.next[0].next) {
            if (lookup[node.key] === i) {
                result.push(node.key);
            }
        }
        return result;
    }
 
    private static binaryIntersect(a: Node, b: Node): Node[] {
        const lookup: any = Object.create(null),
            result: Node[] = [];
        for (; a; a = a.next[0].next) {
            lookup[a.key] = true;
        }
        for (; b; b = b.next[0].next) {
            if (lookup[b.key]) {
                result.push(b.key);
            }
        }
        return result;
    }
 
    private static ternaryIntersect(a: Node, b: Node, c: Node): Node[] {
        const lookup: any = Object.create(null),
            result: Node[] = [];
        for (; a; a = a.next[0].next) {
            lookup[a.key] = 0;
        }
        for (; b; b = b.next[0].next) {
            if (lookup[b.key] === 0) {
                lookup[b.key] = 1;
            }
        }
        for (; c; c = c.next[0].next) {
            if (lookup[c.key] === 1) {
                result.push(c.key);
            }
        }
        return result;
    }
 
  public length: number = 0;
 
  public _unique: boolean = false;
 
  /*
   * NOTE: These two are initialized only to get around Typescript's aggressive checking
   * for initialization.  They are also made public to satisfy the unit tests.
   */
  public _head: Node = new Node(
      0,
      null,
      0
  );
 
  public _tail: Node = new Node(
      0,
      null,
      0
  );
 
  public _level: number = 1;
 
  private _map: any;
 
  constructor(options: any = {"unique": false}) {
      this._unique = Boolean(options.unique);
      this.empty();
  }
 
  public [Symbol.iterator]() {
      let pointer: number = 0;
      const items: any = this._map;
      return {
 
          /**
           * @hidden
           */
          next(): IteratorResult<any> {
              if (pointer < Object.keys(items).length) {
                  return {
                      "done": false,
                      "value": items[Object.keys(items)[pointer++]]
                  };
              }
 
              return {
                  "done": true,
                  "value": null
              };
          }
      };
  }
 
  public add(key: string, value?: number | null): any {
      let current;
 
      /*
       * If (key === '__proto__') {
       *   Throw new Error('invalid key __proto__');
       * }
       */
 
      if (value == null || value === undefined) {
          return this.rem(key);
      }
 
      current = this._map[key];
 
      if (current !== undefined) {
          if (value === current) {
              return current;
          }
          this._remove(
              key,
              current
          );
      }
 
      const node = this._insert(
          key,
          value
      );
      if (!node) {
          Eif (current === undefined || this._insert(
              key,
              current
          )) {
              // TODO: can we defer _remove until after insert?
              throw new Error("unique constraint violated");
          }
      }
 
      this._map[key] = value;
      return current === undefined
          ? null
          : current;
  }
 
  public addAll(sortedSet: SortedSet): void {
      for (const key of sortedSet.keys()) {
          const value = sortedSet.get(key);
          this.add(
              key,
              value
          );
      }
  }
 
  public card(): number {
      // Returns the sorted set cardinality (number of elements)
      Eif (this.length) {
          return this.length;
      }
      return 0;
  }
 
  /**
   * Return the number of elements with a score between
   * min and max scores.  Inclusive.
   * @param min the minimum score
   * @param max the maximum score
   */
 
  public count(min?: number, max?: number): number {
      if (!this.length) {
          return 0;
      }
 
      if (min == null) {
          min = -Infinity;
      }
      if (max == null) {
          max = Infinity;
      }
 
      if (min <= this._head.next[0].next.value && max >= this._tail.value) {
          return this.length;
      }
 
      if (max < min || min > this._tail.value || max < this._head.next[0].next.value) {
          return 0;
      }
 
      let i,
          node = this._first(min),
          count = 0;
 
      Iif (!node) {
          return 0;
      }
 
      for (i = node.next.length - 1; i >= 0; i -= 1) {
          while (node.next[i].next && node.next[i].next.value <= max) {
              count += node.next[i].span;
              node = node.next[i].next;
          }
      }
 
      // Feels hacky and error prone
      return count && count + 1;
  }
 
  public del(key: string): number {
      // Alias for .rem
      return this.rem(key);
  }
 
  public empty(): void {
      this.length = 0;
      this._level = 1;
      this._map = Object.create(null);
      this._head = new Node(
          32,
          null,
          0
      );
      this._tail = null as any as Node;
 
      for (let i = 0; i < 32; i += 1) {
          // Hrm
          this._head.next[i] = new Level(
null as any as Node,
0
          );
      }
  }
 
  public get(key: string): number {
      // Alias for
      return this.score(key);
  }
 
  public has(key: string): boolean {
      return this._map[key] !== undefined;
  }
 
  public incrBy(increment: number, key: string): number {
      /*
       * Increases the score of the member specified by key.
       * If member does not exist, a new member is created with
       * The increment as its score.
       *
       * Parameters:
       *   Increment
       *     Number
       *   Key
       *     String
       *
       * Return
       *   Number, the new score of the member
       *
       * TODO: Shortcut, could optimize to half
       */
 
      const score = this.score(key);
 
      if (score) {
          this.add(
              key,
              score + increment
          );
          return score + increment;
      }
 
      this.add(
          key,
          increment
      );
      return increment;
  }
 
  public keys(): string[] {
      if (!this.length) {
          return [];
      }
 
      let i;
      const array = new Array(this.length);
      let node = this._head.next[0].next;
 
      for (i = 0; node; node = node.next[0].next) {
          array[i] = node.key;
          i += 1;
      }
 
      return array;
  }
 
  public range(start?: number, stop?: number, options?: any): Node[] {
      /*
       * Parameters:
       *   Start
       *     Inclusive
       *   Stop
       *     Inclusive
       *   Options (optional)
       *     WithScores (optional, default to false)
       *
       * Return:
       *   An array
       */
      let result;
 
      if (this.length === 0) {
          return [];
      }
 
      if (start == null) {
          start = 0;
      } else if (start < 0) {
          start = Math.max(
              this.length + start,
              0
          );
      }
 
      if (stop == null) {
          stop = this.length - 1;
      } else if (stop < 0) {
          stop = this.length + stop;
      }
 
      if (start > stop || start >= this.length) {
          return [];
      }
 
      if (stop >= this.length) {
          stop = this.length - 1;
      }
 
      if (typeof options !== "object") {
          options = {
              "withScores": false
          };
      }
 
      let i = 0,
          length = stop - start + 1;
      try {
          result = new Array(length);
      } catch (e) {
          /*
           * Console.log('start', start);
           * console.log('stop', stop);
           * console.log('Invalid length', length);
           */
          throw e;
      }
 
      let node = start > 0
          ? this._get(start)
          : this._head.next[0].next;
 
      if (options.withScores) {
          for (; length--; node = node.next[0].next) {
              result[i] = [
                  node.key,
                  node.value
              ];
              i += 1;
          }
      } else {
          for (; length--; node = node.next[0].next) {
              result[i] = node.key;
              i += 1;
          }
      }
 
      return result;
  }
 
  public rangeByScore(min?: number | null, max?: number | null, options?: any): Node[] {
      /*
       * Return members with score within inclusive range [min, max].
       *
       * Parameters:
       *   Min (number)
       *   Max (number)
       *   Options (object, optional)
       *     WithScores (bool, optional, default false)
       */
      const maxExclusive: boolean = options && Boolean(options.maxExclusive),
          minExclusive: boolean = options && Boolean(options.minExclusive);
 
      if (!this.length) {
          return [];
      }
 
      if (typeof options !== "object") {
          options = {
              "withScores": false
          };
      }
 
      if (min == null) {
          min = -Infinity;
      }
      if (max == null) {
          max = Infinity;
      }
 
      if (!minExclusive && min <= this._head.next[0].next.value && !maxExclusive && max >= this._tail.value) {
          return this.toArray({"withScores": options.withScores});
      }
 
      if (max < min || min > this._tail.value || max < this._head.next[0].next.value) {
          return [];
      }
 
      let node = this._first(min);
      const result = [];
 
      if (options.withScores) {
          for (; node && node.value <= max; node = node.next[0].next) {
              let pushit: boolean = true;
              Iif (minExclusive && node.value === min) {
                  pushit = false;
              } else Iif (maxExclusive && node.value === max) {
                  pushit = false;
              }
              Eif (pushit) {
                  result.push([
                      node.key,
                      node.value
                  ]);
              }
          }
      } else {
          for (; node && node.value <= max; node = node.next[0].next) {
              let pushit: boolean = true;
              Iif (minExclusive && node.value === min) {
                  pushit = false;
              } else Iif (maxExclusive && node.value === max) {
                  pushit = false;
              }
              Eif (pushit) {
                  result.push(node.key);
              }
          }
      }
 
      return result;
  }
 
  public rank(key: string): number {
      /*
       * Rank of key, ordered by value.
       *
       * Return
       *   Integer
       *     If member exists
       *  Null
       *     If member does not exist
       */
 
      const value = this._map[key];
 
      if (value === undefined) {
          return null as any as number;
      }
 
      let i,
          node = this._head,
          next = null,
          rank = -1;
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          while ((next = node.next[i].next) && (next.value < value || next.value === value && next.key <= key)) {
              rank += node.next[i].span;
              node = next;
          }
          if (node.key && node.key === key) {
              return rank;
          }
      }
 
      return null as any as number;
  }
 
  public rem(key: string): number {
      /*
       * Remove single member by key.
       *
       * Return
       *   Value of the removed key
       *   Or null if key does not exist.
       */
 
      const value = this._map[key];
      if (value !== undefined) {
          this._remove(
              key,
              value
          );
          delete this._map[key];
          return value;
      }
      return null as any as number;
  }
 
  public remRangeByRank(start: number, end: number): number {
      /*
       * Parameters:
       *   Start
       *     Inclusive
       *   End
       *     Exclusive
       *
       * Return
       *   Positive integer, the number of removed keys.
       */
 
      const len = this.length;
 
      Iif (!len) {
          return 0;
      }
 
      Iif (start == null) {
          start = 0;
      } else Iif (start < 0) {
          start = Math.max(
              len + start,
              0
          );
      }
 
      Iif (end == null) {
          end = len;
      } else Iif (end < 0) {
          end = len + end;
      }
 
      Iif (start > end || start >= len) {
          return 0;
      }
      Iif (end > len) {
          end = len;
      }
 
      if (start === 0 && end === len) {
          this.empty();
          return len;
      }
 
      let node = this._head;
      const update = new Array(32);
      let i: number,
          next,
          traversed = -1;
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          while ((next = node.next[i].next) && traversed + node.next[i].span < start) {
              traversed += node.next[i].span;
              node = next;
          }
          update[i] = node;
      }
 
      let removed = 0;
      traversed += 1;
      node = node.next[0].next;
 
      while (node && traversed < end) {
          next = node.next[0].next;
          this._removeNode(
              node,
              update
          );
          delete this._map[node.key];
          removed += 1;
          traversed += 1;
          node = next;
      }
 
      this.length -= removed;
      return removed;
  }
 
  public remRangeByScore(min: number, max: number): number {
      /*
       * Remove members with value between min and max (inclusive).
       *
       * Return
       *   Positive integer, the number of removed elements.
       */
 
      let removed = 0;
 
      Iif (!this.length) {
          return 0;
      }
 
      Iif (min == null) {
          min = -Infinity;
      }
      Iif (max == null) {
          max = Infinity;
      }
 
      if (min <= this._head.next[0].next.value && max >= this._tail.value) {
          removed = this.length;
          this.empty();
          return removed;
      }
 
      let next,
          i,
          node = this._head;
      const update = new Array(32);
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          while ((next = node.next[i].next) && next.value < min) {
              node = next;
          }
          update[i] = node;
      }
      node = node.next[0].next;
 
      while (node && node.value <= max) {
          next = node.next[0].next;
          this._removeNode(
              node,
              update
          );
          delete this._map[node.key];
          removed += 1;
          node = next;
      }
 
      this.length -= removed;
      return removed;
  }
 
  public score(key: string): number {
      /*
       * Return
       *   Number, the score of member in the sorted set.
       *   Null, if member does not exist in the sorted set.
       */
      const score = this._map[key];
      return score === undefined
          ? null
          : score;
  }
 
  public set(key: string, value: number): number {
      // Alias for
      return this.add(
          key,
          value
      );
  }
 
  public slice(start: number, end: number, options?: any): Node[] {
      /*
       * Almost alias for range. Only difference is that
       * The end is exclusive i.e. not included in the range.
       */
      Eif (typeof end === "number" && end !== 0) {
          end -= 1;
      }
      return this.range(
          start,
          end,
          options
      );
  }
 
  public toArray(options?: any): Node[] {
      /*
       * The whole set, ordered from smallest to largest.
       *
       * Parameters
       *   Options (optional)
       *     WithScores (optional, default false)
       *       Bool
       */
 
      if (!this.length) {
          return [];
      }
 
      if (typeof options !== "object") {
          options = {
              "withScores": false
          };
      }
 
      let i;
      const array = new Array(this.length);
      let node = this._head.next[0].next;
 
      if (options.withScores) {
          for (i = 0; node; node = node.next[0].next) {
              array[i] = [
                  node.key,
                  node.value
              ];
              i += 1;
          }
      } else {
          for (i = 0; node; node = node.next[0].next) {
              array[i] = node.key;
              i += 1;
          }
      }
 
      return array;
  }
 
  public values(): number[] {
      // Return values as an array, the smallest value first.
 
      Iif (!this.length) {
          return [];
      }
 
      let i;
      const array = new Array(this.length);
      let node = this._head.next[0].next;
 
      for (i = 0; node; node = node.next[0].next) {
          array[i] = node.value;
          i += 1;
      }
 
      return array;
  }
 
  private _first(min: number): Node {
      let next,
          node = this._tail;
 
      Iif (!node || node.value < min) {
          return null as any as Node;
      }
 
      node = this._head;
      let i: number;
      for (next = null, i = this._level - 1; i >= 0; i -= 1) {
          while ((next = node.next[i].next) && next.value < min) {
              node = next;
          }
      }
 
      return node.next[0].next;
  }
 
  private _get(index: number): Node {
      /*
       * Find and return the node at index.
       * Return null if not found.
       *
       * TODO: optimize when index is less than log(N) from the end
       */
      let i,
          node = this._head,
          distance = -1;
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          while (node.next[i].next && distance + node.next[i].span <= index) {
              distance += node.next[i].span;
              node = node.next[i].next;
          }
          if (distance === index) {
              return node;
          }
      }
      return null as any as Node;
  }
 
  private _insert(key: string, value: number): any {
      assert.notEqual(
          value,
          undefined,
          "Value is unexpectedly undefined"
      );
 
      /*
       * Precondition: does not already have key
       * In unique mode, returns null if the value already exists
       */
      const update = new Array(32),
          rank = new Array(32);
      let node = this._head,
          next = null,
          i;
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          rank[i] = i === this._level - 1
              ? 0
              : rank[i + 1];
          // TODO: optimize some more?
          Eif (node) {
              while ((next = node.next[i].next) && next.value <= value) {
                  if (next.value === value) {
                      if (this._unique) {
                          return null;
                      }
                      if (next.key >= key) {
                          break;
                      }
                  }
                  rank[i] += node.next[i].span;
                  node = next;
              }
          }
          Iif (this._unique && node.value === value) {
              return null as any as Node;
          }
          update[i] = node;
      }
 
      Iif (this._unique && node.value === value) {
          return null as any as Node;
      }
 
      const level = this.randomLevel();
      if (level > this._level) {
          // TODO: optimize
          for (i = this._level; i < level; i += 1) {
              rank[i] = 0;
              update[i] = this._head;
              update[i].next[i].span = this.length;
          }
          this._level = level;
      }
 
      node = new Node(
          level,
          key,
          value
      );
      for (i = 0; i < level; i += 1) {
          node.next[i] = new Level(
              update[i].next[i].next,
              update[i].next[i].span - (rank[0] - rank[i])
          );
          update[i].next[i].next = node;
          update[i].next[i].span = rank[0] - rank[i] + 1;
      }
 
      for (i = level; i < this._level; i += 1) {
          update[i].next[i].span++;
      }
 
      node.prev = update[0] === this._head
          ? null
          : update[0];
      if (node.next[0].next) {
          node.next[0].next.prev = node;
      } else {
          this._tail = node;
      }
 
      this.length += 1;
      return node;
  }
 
  private _remove(key: string, value: number): void {
      // Z.prototype._remove = function (key, value) {
      const update = new Array(32);
      let node = this._head,
          i: number,
          next: Node;
 
      for (i = this._level - 1; i >= 0; i -= 1) {
          while ((next = node.next[i].next) && (next.value < value || next.value === value && next.key < key)) {
              node = next;
          }
          update[i] = node;
      }
 
      node = node.next[0].next;
 
      Iif (!node || value !== node.value || node.key !== key) {
          return; // False;
      }
 
      // Delete
      this._removeNode(
          node,
          update
      );
      this.length -= 1;
  }
 
  private _removeNode(node: Node, update: Node[]): void {
      // Z.prototype._removeNode = function (node, update) {
      let i = 0,
          next = null;
      const n = this._level;
 
      for (; i < n; i += 1) {
          if (update[i].next[i].next === node) {
              update[i].next[i].span += node.next[i].span - 1;
              update[i].next[i].next = node.next[i].next;
          } else {
              update[i].next[i].span -= 1;
          }
      }
      next = node.next[0].next;
      if (next) {
          next.prev = node.prev;
      } else {
          this._tail = node.prev;
      }
 
      while (this._level > 1 && !this._head.next[this._level - 1].next) {
          this._level -= 1;
      }
  }
 
  private randomLevel(): number {
      let level = 1;
      while (Math.random() < 1 / Math.E) {
          level += 1;
      }
      return level < 32
          ? level
          : 32;
  }
}