All files / core/domain/classes Graph.ts

89.27% Statements 258/289
77.14% Branches 108/140
94.12% Functions 32/34
88.69% Lines 243/274

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  6x     6x   6x 6x 6x         6x           6x     66x                                 1967x   670x 670x 100x   100x         670x     664x 664x 199x   199x         664x                                           6x 42x         42x 42x             42x 42x               42x 42x 42x   42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x     42x 24x   24x         42x 500x         500x                               6x   160x     160x     160x 1x   159x 159x     159x 74x   164x     85x       69x       69x       69x       69x         90x 90x 90x 90x       159x 159x 159x   159x 159x 159x     159x 159x     159x                                 6x   174x     174x     174x           174x           174x 1x   173x     173x 80x 262x 22x   93x       73x         73x         73x         73x         100x 100x 100x 100x       173x 173x   173x 173x     173x       173x 173x     173x       173x 173x     173x         147x 147x     147x           173x 173x 173x 173x   173x                     6x   6x           6x 1x   5x     5x 5x   5x 5x       5x 14x 7x     5x 5x 5x   5x 5x 5x   5x 11x 11x 11x     5x                   6x   11x           11x 1x     10x 10x 10x   10x 10x     10x 10x 10x   10x 10x 10x   10x 10x 10x     8x 8x 8x     10x 10x 10x 10x   10x             6x                                               6x 10x 10x         10x 10x 10x 10x 10x 10x 10x 10x 10x   10x                                                               14x 61x 59x 14x                           402x   148x   100x   105x   1x                             6x           81x       81x                                                       119x   50x   15x   18x   1x                                                   6x 7x             7x 1x   6x 6x 6x       6x 60x     60x     60x 60x 60x                               6x 5x                                                                                           6x             10x                       1x     1x   2x     1x     5x     8x 2x       6x 6x           6x 3x                                                                           6x 1x                       1x     1x       4x     1x   6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x  
import { Edge, Node, Keyed } from "../../interfaces";
import emptyObject from "../utils/misc/emptyObject";
type NamedBindings = Keyed<Function | null>;
 
const _methods: NamedBindings = Object.create(null);
// tracks binding objects that have been registered.
const _indexes: Set<string> = new Set();
const _initBindings: NamedBindings = Object.create(null);
const _methodBindings: { [methodName: string]: NamedBindings } = Object.create(
  null
);
const _methodBeforeBindings: {
  [methodName: string]: NamedBindings;
} = Object.create(null);
const _defaultSettings: Keyed<any> = {
  immutable: true,
  clone: true
};
 
const _defaultSettingsFunction = function _defaultSettingsFunction(
  key: string
) {
  return _defaultSettings[key];
};
 
/**
 * A custom tool to bind methods such that function that are bound to it will
 * be executed anytime the method is called.
 *
 * @param  {string}   methodName The name of the method to bind.
 * @param  {object}   scope      The scope where the method must be executed.
 * @param  {function} fn         The method itself.
 * @return {function}            The new method.
 */
function bindGraphMethod(
  methodName: string,
  scope: any,
  fn: Function
): Function {
  return (...boundArgs: any[]) => {
    // Execute "before" bound functions:
    const beforeBindings = _methodBeforeBindings[methodName];
    Object.keys(beforeBindings).forEach(k => {
      const fn = beforeBindings[k];
      if (fn) {
        fn.apply(scope, boundArgs);
      }
    });
 
    // Apply the method:
    const res = fn.apply(scope, boundArgs);
 
    // Execute bound functions:
    const methodBindings = _methodBindings[methodName];
    Object.keys(methodBindings).forEach(k => {
      const fn = methodBindings[k];
      if (fn) {
        fn.apply(scope, boundArgs);
      }
    });
 
    // Return res:
    return res;
  };
}
 
/**
 * The graph constructor. It initializes the data and the indexes, and binds
 * the custom indexes and methods to its own scope.
 *
 * Recognized parameters:
 * **********************
 * Here is the exhaustive list of every accepted parameters in the settings
 * object:
 *
 *   {boolean} clone     Indicates if the data have to be cloned in methods
 *                       to add nodes or edges.
 *   {boolean} immutable Indicates if nodes "id" values and edges "id",
 *                       "source" and "target" values must be set as
 *                       immutable.
 *
 * @param  {?configurable} settings Eventually a settings function.
 * @return {graph}                  The new graph instance.
 */
class Graph {
  public settings = _defaultSettingsFunction;
  /**
   * MAIN DATA:
   * **********
   */
  public nodesArray: Node[] = [];
  public edgesArray: Edge[] = [];
 
  /**
   * GLOBAL INDEXES:
   * ***************
   * These indexes just index data by ids.
   */
  public nodesIndex: Keyed<Node> = Object.create(null);
  public edgesIndex: Keyed<Edge> = Object.create(null);
 
  /**
   * LOCAL INDEXES:
   * **************
   * These indexes refer from node to nodes. Each key is an id, and each
   * value is the array of the ids of related nodes.
   */
  public inNeighborsIndex: Keyed<Keyed<Keyed<number>>> = Object.create(null);
  public outNeighborsIndex: Keyed<Keyed<Keyed<number>>> = Object.create(null);
  public allNeighborsIndex: Keyed<Keyed<Keyed<number>>> = Object.create(null);
 
  public inNeighborsCount: Keyed<number> = Object.create(null);
  public outNeighborsCount: Keyed<number> = Object.create(null);
  public allNeighborsCount: Keyed<number> = Object.create(null);
 
  constructor(settings?: any) {
    this.settings = settings || _defaultSettingsFunction;
    this.addNode = this.addNode.bind(this);
    this.addEdge = this.addEdge.bind(this);
    this.dropNode = this.dropNode.bind(this);
    this.dropEdge = this.dropEdge.bind(this);
    this.kill = this.kill.bind(this);
    this.clear = this.clear.bind(this);
    this.read = this.read.bind(this);
    this.nodes = this.nodes.bind(this);
    this.degree = this.degree.bind(this);
    this.edges = this.edges.bind(this);
 
    // Execute bindings:
    Object.keys(_initBindings).forEach(k => {
      const fn = _initBindings[k];
      if (fn) {
        fn.call(this);
      }
    });
 
    // Add methods to both the scope and the data objects:
    Object.keys(_methods).forEach(methodName => {
      const method = bindGraphMethod(
        methodName,
        this,
        _methods[methodName] || (this as any)[methodName]
      );
      (this as any)[methodName] = method;
    });
  }
 
  /**
   * This method adds a node to the graph. The node must be an object, with a
   * string under the key "id". Except for this, it is possible to add any
   * other attribute, that will be preserved all along the manipulations.
   *
   * If the graph option "clone" has a truthy value, the node will be cloned
   * when added to the graph. Also, if the graph option "immutable" has a
   * truthy value, its id will be defined as immutable.
   *
   * @param  {object} node The node to add.
   * @return {object}      The graph instance.
   */
  public addNode(node: Partial<Node>) {
    // Check that the node is an object and has an id:
    Iif (Object(node) !== node || arguments.length !== 1)
      throw new Error("addNode: Wrong arguments.");
 
    Iif (typeof node.id !== "string" && typeof node.id !== "number")
      throw new Error("The node must have a string or number id.");
 
    if (this.nodesIndex[node.id])
      throw new Error(`The node "${node.id}" already exists.`);
 
    const { id, type, size, label } = node;
    let validNode = Object.create(null);
 
    // Check the "clone" option:
    if (this.settings("clone")) {
      Object.keys(node).forEach(k => {
        if (k !== "id") {
          validNode[k] = node[k];
        }
      });
    } else validNode = node;
 
    // Check the "immutable" option:
    if (this.settings("immutable")) {
      Object.defineProperty(validNode, "id", {
        value: id,
        enumerable: true
      });
      Object.defineProperty(validNode, "type", {
        value: type || "def",
        enumerable: true
      });
      Object.defineProperty(validNode, "size", {
        value: size || 5,
        enumerable: true
      });
      Object.defineProperty(validNode, "label", {
        value: label || `${id}`,
        enumerable: true
      });
    } else {
      validNode.id = id;
      validNode.type = type || "def";
      validNode.size = size || 5;
      validNode.label = label || `${id}`;
    }
 
    // Add empty containers for edges indexes:
    this.inNeighborsIndex[id] = Object.create(null);
    this.outNeighborsIndex[id] = Object.create(null);
    this.allNeighborsIndex[id] = Object.create(null);
 
    this.inNeighborsCount[id] = 0;
    this.outNeighborsCount[id] = 0;
    this.allNeighborsCount[id] = 0;
 
    // Add the node to indexes:
    this.nodesArray.push(validNode);
    this.nodesIndex[validNode.id] = validNode;
 
    // Return the current instance:
    return this;
  }
 
  /**
   * This method adds an edge to the graph. The edge must be an object, with a
   * string under the key "id", and strings under the keys "source" and
   * "target" that design existing nodes. Except for this, it is possible to
   * add any other attribute, that will be preserved all along the
   * manipulations.
   *
   * If the graph option "clone" has a truthy value, the edge will be cloned
   * when added to the graph. Also, if the graph option "immutable" has a
   * truthy value, its id, source and target will be defined as immutable.
   *
   * @param  {object} edge The edge to add.
   * @return {object}      The graph instance.
   */
  public addEdge(edge: Partial<Edge>) {
    // Check that the edge is an object and has an id:
    Iif (Object(edge) !== edge || arguments.length !== 1)
      throw new Error("addEdge: Wrong arguments.");
 
    Iif (typeof edge.id !== "string" && typeof edge.id !== "number")
      throw new Error("The edge must have a string or number id.");
 
    Iif (
      (typeof edge.source !== "string" && typeof edge.source !== "number") ||
      !this.nodesIndex[edge.source]
    )
      throw new Error("The edge source must have an existing node id.");
 
    Iif (
      (typeof edge.target !== "string" && typeof edge.target !== "number") ||
      !this.nodesIndex[edge.target]
    )
      throw new Error("The edge target must have an existing node id.");
 
    if (this.edgesIndex[edge.id])
      throw new Error(`The edge "${edge.id}" already exists.`);
 
    let validEdge = Object.create(null);
 
    // Check the "clone" option:
    if (this.settings("clone")) {
      Object.keys(edge).forEach(k => {
        if (k !== "id" && k !== "source" && k !== "target")
          validEdge[k] = edge[k];
      });
    } else validEdge = edge;
 
    // Check the "immutable" option:
    if (this.settings("immutable")) {
      Object.defineProperty(validEdge, "id", {
        value: edge.id,
        enumerable: true
      });
 
      Object.defineProperty(validEdge, "type", {
        value: edge.type || "def",
        enumerable: true
      });
 
      Object.defineProperty(validEdge, "source", {
        value: edge.source,
        enumerable: true
      });
 
      Object.defineProperty(validEdge, "target", {
        value: edge.target,
        enumerable: true
      });
    } else {
      validEdge.id = edge.id;
      validEdge.source = edge.source;
      validEdge.target = edge.target;
      validEdge.type = edge.type || "def";
    }
 
    // Add the edge to indexes:
    this.edgesArray.push(validEdge);
    this.edgesIndex[validEdge.id] = validEdge;
 
    Eif (!this.inNeighborsIndex[validEdge.target][validEdge.source])
      this.inNeighborsIndex[validEdge.target][validEdge.source] = Object.create(
        null
      );
    this.inNeighborsIndex[validEdge.target][validEdge.source][
      validEdge.id
    ] = validEdge;
 
    Eif (!this.outNeighborsIndex[validEdge.source][validEdge.target])
      this.outNeighborsIndex[validEdge.source][
        validEdge.target
      ] = Object.create(null);
    this.outNeighborsIndex[validEdge.source][validEdge.target][
      validEdge.id
    ] = validEdge;
 
    Eif (!this.allNeighborsIndex[validEdge.source][validEdge.target])
      this.allNeighborsIndex[validEdge.source][
        validEdge.target
      ] = Object.create(null);
    this.allNeighborsIndex[validEdge.source][validEdge.target][
      validEdge.id
    ] = validEdge;
 
    if (validEdge.target !== validEdge.source) {
      Eif (!this.allNeighborsIndex[validEdge.target][validEdge.source])
        this.allNeighborsIndex[validEdge.target][
          validEdge.source
        ] = Object.create(null);
      this.allNeighborsIndex[validEdge.target][validEdge.source][
        validEdge.id
      ] = validEdge;
    }
 
    // Keep counts up to date:
    this.inNeighborsCount[validEdge.target]++;
    this.outNeighborsCount[validEdge.source]++;
    this.allNeighborsCount[validEdge.target]++;
    this.allNeighborsCount[validEdge.source]++;
 
    return this;
  }
 
  /**
   * This method drops a node from the graph. It also removes each edge that is
   * bound to it, through the dropEdge method. An error is thrown if the node
   * does not exist.
   *
   * @param  {string} id The node id.
   * @return {object}    The graph instance.
   */
  public dropNode(id: string) {
    // Check that the arguments are valid:
    Iif (
      (typeof id !== "string" && typeof id !== "number") ||
      arguments.length !== 1
    )
      throw new Error("dropNode: Wrong arguments.");
 
    if (!this.nodesIndex[id])
      throw new Error(`The node "${id}" does not exist.`);
 
    const l = this.nodesArray.length;
 
    // Remove the node from indexes:
    delete this.nodesIndex[id];
    for (let i = 0; i < l; i++)
      if (this.nodesArray[i].id === id) {
        this.nodesArray.splice(i, 1);
        break;
      }
 
    // Remove related edges:
    for (let i = this.edgesArray.length - 1; i >= 0; i--)
      if (this.edgesArray[i].source === id || this.edgesArray[i].target === id)
        this.dropEdge(this.edgesArray[i].id);
 
    // Remove related edge indexes:
    delete this.inNeighborsIndex[id];
    delete this.outNeighborsIndex[id];
    delete this.allNeighborsIndex[id];
 
    delete this.inNeighborsCount[id];
    delete this.outNeighborsCount[id];
    delete this.allNeighborsCount[id];
 
    Object.keys(this.nodesIndex).forEach(k => {
      delete this.inNeighborsIndex[k][id];
      delete this.outNeighborsIndex[k][id];
      delete this.allNeighborsIndex[k][id];
    });
 
    return this;
  }
 
  /**
   * This method drops an edge from the graph. An error is thrown if the edge
   * does not exist.
   *
   * @param  {string} id The edge id.
   * @return {object}    The graph instance.
   */
  public dropEdge(id: string) {
    // Check that the arguments are valid:
    Iif (
      (typeof id !== "string" && typeof id !== "number") ||
      arguments.length !== 1
    )
      throw new Error("dropEdge: Wrong arguments.");
 
    if (!this.edgesIndex[id])
      throw new Error(`The edge "${id}" does not exist.`);
 
    // Remove the edge from indexes:
    const edge = this.edgesIndex[id];
    delete this.edgesIndex[id];
    for (let i = 0; i < this.edgesArray.length; i++)
      if (this.edgesArray[i].id === id) {
        this.edgesArray.splice(i, 1);
        break;
      }
 
    delete this.inNeighborsIndex[edge.target][edge.source][edge.id];
    Eif (!Object.keys(this.inNeighborsIndex[edge.target][edge.source]).length)
      delete this.inNeighborsIndex[edge.target][edge.source];
 
    delete this.outNeighborsIndex[edge.source][edge.target][edge.id];
    Eif (!Object.keys(this.outNeighborsIndex[edge.source][edge.target]).length)
      delete this.outNeighborsIndex[edge.source][edge.target];
 
    delete this.allNeighborsIndex[edge.source][edge.target][edge.id];
    Eif (!Object.keys(this.allNeighborsIndex[edge.source][edge.target]).length)
      delete this.allNeighborsIndex[edge.source][edge.target];
 
    if (edge.target !== edge.source) {
      delete this.allNeighborsIndex[edge.target][edge.source][edge.id];
      Eif (!Object.keys(this.allNeighborsIndex[edge.target][edge.source]).length)
        delete this.allNeighborsIndex[edge.target][edge.source];
    }
 
    this.inNeighborsCount[edge.target]--;
    this.outNeighborsCount[edge.source]--;
    this.allNeighborsCount[edge.source]--;
    this.allNeighborsCount[edge.target]--;
 
    return this;
  }
 
  /**
   * This method destroys the current instance. It basically empties each index
   * and methods attached to the graph.
   */
  public kill() {
    // Delete arrays:
    this.nodesArray.length = 0;
    this.edgesArray.length = 0;
    delete this.nodesArray;
    delete this.edgesArray;
 
    // Delete indexes:
    delete this.nodesIndex;
    delete this.edgesIndex;
    delete this.inNeighborsIndex;
    delete this.outNeighborsIndex;
    delete this.allNeighborsIndex;
    delete this.inNeighborsCount;
    delete this.outNeighborsCount;
    delete this.allNeighborsCount;
  }
 
  /**
   * This method empties the nodes and edges arrays, as well as the different
   * indexes.
   *
   * @return {object} The graph instance.
   */
  public clear() {
    this.nodesArray.length = 0;
    this.edgesArray.length = 0;
 
    // Due to GC issues, I prefer not to create new object. These objects are
    // only available from the methods and attached functions, but still, it is
    // better to prevent ghost references to unrelevant data...
    emptyObject(this.nodesIndex);
    emptyObject(this.edgesIndex);
    emptyObject(this.nodesIndex);
    emptyObject(this.inNeighborsIndex);
    emptyObject(this.outNeighborsIndex);
    emptyObject(this.allNeighborsIndex);
    emptyObject(this.inNeighborsCount);
    emptyObject(this.outNeighborsCount);
    emptyObject(this.allNeighborsCount);
 
    return this;
  }
 
  /**
   * This method reads an object and adds the nodes and edges, through the
   * proper methods "addNode" and "addEdge".
   *
   * Here is an example:
   *
   *  > var myGraph = new graph();
   *  > myGraph.read({
   *  >   nodes: [
   *  >     { id: 'n0' },
   *  >     { id: 'n1' }
   *  >   ],
   *  >   edges: [
   *  >     {
   *  >       id: 'e0',
   *  >       source: 'n0',
   *  >       target: 'n1'
   *  >     }
   *  >   ]
   *  > });
   *  >
   *  > console.log(
   *  >   myGraph.nodes().length,
   *  >   myGraph.edges().length
   *  > ); // outputs 2 1
   *
   * @param  {object} g The graph object.
   * @return {object}   The graph instance.
   */
  public read(g: { nodes?: Partial<Node>[]; edges?: Partial<Edge>[] }) {
    (g.nodes || []).forEach(n => this.addNode(n));
    (g.edges || []).forEach(e => this.addEdge(e));
    return this;
  }
 
  /**
   * This methods returns one or several nodes, depending on how it is called.
   *
   * To get the array of nodes, call "nodes" without argument. To get a
   * specific node, call it with the id of the node. The get multiple node,
   * call it with an array of ids, and it will return the array of nodes, in
   * the same order.
   *
   * @param  {?(string|array)} ids Eventually one id, an array of ids.
   * @return {object|array}      The related node or array of nodes.
   */
  public nodes(...ids: string[]): Node[] {
    // Clone the array of nodes and return it:
    if (!ids.length) return this.nodesArray.slice(0);
 
    return (ids as string[]).map(id => {
      if (typeof id === "string" || typeof id === "number") {
        return this.nodesIndex[id];
      } else {
        throw new Error("nodes: Wrong arguments.");
      }
    });
  }
 
  /**
   * This methods returns the degree of one or several nodes, depending on how
   * it is called. It is also possible to get incoming or outcoming degrees
   * instead by specifying 'in' or 'out' as a second argument.
   *
   * @param  {string|array} v     One id, an array of ids.
   * @param  {?string}      which Which degree is required. Values are 'in',
   *                              'out', and by default the normal degree.
   * @return {number|array}       The related degree or array of degrees.
   */
  public degree(v: string | string[], inWhich?: "in" | "out") {
    // Check which degree is required:
    const whichMap: Keyed<Keyed<number>> = {
      in: this.inNeighborsCount,
      out: this.outNeighborsCount
    };
    const which = inWhich ? whichMap[inWhich] : this.allNeighborsCount;
 
    // Return the related node:
    if (typeof v === "string" || typeof v === "number") {
      return which[v];
    }
 
    // Return an array of the related node:
    if (Object.prototype.toString.call(v) === "[object Array]") {
      return (v as string[]).map(arg => {
        if (typeof arg === "string" || typeof arg === "number") {
          return which[arg];
        } else {
          throw new Error("degree: Wrong arguments.");
        }
      });
    }
 
    throw new Error("degree: Wrong arguments.");
  }
 
  /**
   * This methods returns one or several edges, depending on how it is called.
   *
   * To get the array of edges, call "edges" without argument. To get a
   * specific edge, call it with the id of the edge. The get multiple edge,
   * call it with an array of ids, and it will return the array of edges, in
   * the same order.
   *
   * @param  {?(string|array)} ids Eventually one id, an array of ids.
   * @return {array}      The related edge or array of edges.
   */
  public edges(...ids: string[]): Edge[] {
    // Clone the array of edges and return it:
    if (!ids.length) return this.edgesArray.slice(0);
 
    return (ids as any[]).map(id => {
      if (typeof id === "string" || typeof id === "number") {
        return this.edgesIndex[id];
      } else {
        throw new Error("edges: Wrong arguments.");
      }
    });
  }
 
  /**
   * This global method adds a method that will be bound to the futurly created
   * graph instances.
   *
   * Since these methods will be bound to their scope when the instances are
   * created, it does not use the prototype. Because of that, methods have to
   * be added before instances are created to make them available.
   *
   * Here is an example:
   *
   *  > Graph.enableHooks('getNodesCount', function() {
   *  >   return this.nodesArray.length;
   *  > });
   *  >
   *  > var myGraph = new graph();
   *  > console.log(myGraph.getNodesCount()); // outputs 0
   *
   * @param  {string}   methodName The name of the method.
   * @param  {function} fn         The method itself.
   * @return {object}              The global graph constructor.
   */
  public static addMethod(methodName: string, fn: Function) {
    Iif (
      typeof methodName !== "string" ||
      typeof fn !== "function" ||
      arguments.length !== 2
    )
      throw new Error("addMethod: Wrong arguments.");
 
    if (_methods[methodName] || (Graph as any)[methodName]!)
      throw new Error(`The method "${methodName}" already exists.`);
 
    _methods[methodName] = fn;
    _methodBindings[methodName] = {};
    _methodBeforeBindings[methodName] = {};
  }
 
  /** Adds hook infrastructure for a method already specified on the graph class */
  public static __addOwnMethod(methodName: string) {
    Iif (typeof methodName !== "string")
      throw new Error("__addOwnMethod: Wrong arguments.");
 
    Iif (_methods[methodName])
      throw new Error(`The method "${methodName}" already exists.`);
 
    _methods[methodName] = null;
    _methodBindings[methodName] = {};
    _methodBeforeBindings[methodName] = {};
  }
 
  /**
   * This global method returns true if the method has already been added, and
   * false else.
   *
   * Here are some examples:
   *
   *  > graph.hasMethod('addNode'); // returns true
   *  > graph.hasMethod('hasMethod'); // returns true
   *  > graph.hasMethod('unexistingMethod'); // returns false
   *
   * @param  {string}  methodName The name of the method.
   * @return {boolean}            The result.
   */
  public static hasMethod(methodName: string) {
    return !!(_methods[methodName] || (Graph as any)[methodName]);
  }
 
  /**
   * This global methods attaches a function to a method. Anytime the specified
   * method is called, the attached function is called right after, with the
   * same arguments and in the same scope. The attached function is called
   * right before if the last argument is true, unless the method is the graph
   * constructor.
   *
   * To attach a function to the graph constructor, use 'constructor' as the
   * method name (first argument).
   *
   * The main idea is to have a clean way to keep custom indexes up to date,
   * for instance:
   *
   *  > var timesAddNodeCalled = 0;
   *  > graph.attach('addNode', 'timesAddNodeCalledInc', function() {
   *  >   timesAddNodeCalled++;
   *  > });
   *  >
   *  > var myGraph = new graph();
   *  > console.log(timesAddNodeCalled); // outputs 0
   *  >
   *  > myGraph.addNode({ id: '1' }).addNode({ id: '2' });
   *  > console.log(timesAddNodeCalled); // outputs 2
   *
   * The idea for calling a function before is to provide pre-processors, for
   * instance:
   *
   *  > var colorPalette = { Person: '#C3CBE1', Place: '#9BDEBD' };
   *  > graph.attach('addNode', 'applyNodeColorPalette', function(n) {
   *  >   n.color = colorPalette[n.category];
   *  > }, true);
   *  >
   *  > var myGraph = new graph();
   *  > myGraph.addNode({ id: 'n0', category: 'Person' });
   *  > console.log(myGraph.nodes('n0').color); // outputs '#C3CBE1'
   *
   * @param  {string}   methodName The name of the related method or
   *                               "constructor".
   * @param  {string}   key        The key to identify the function to attach.
   * @param  {function} fn         The function to bind.
   * @param  {boolean}  before     If true the function is called right before.
   * @return {object}              The global graph constructor.
   */
  public static attach(
    methodName: string,
    key: string,
    fn: Function,
    before?: boolean
  ) {
    ``;
    Iif (
      typeof methodName !== "string" ||
      typeof key !== "string" ||
      typeof fn !== "function" ||
      arguments.length < 3 ||
      arguments.length > 4
    )
      throw new Error("attach: Wrong arguments.");
 
    let bindings;
 
    if (methodName === "constructor") {
      bindings = _initBindings;
    } else if (before) {
      if (!_methodBeforeBindings[methodName]) {
        throw new Error(`The method "${methodName}" does not exist.`);
      }
      bindings = _methodBeforeBindings[methodName];
    } else {
      if (!_methodBindings[methodName]) {
        throw new Error(`The method "${methodName}" does not exist.`);
      }
 
      bindings = _methodBindings[methodName];
    }
 
    if (bindings[key])
      throw new Error(
        `A function "${key}" is already attached to the method "${methodName}".`
      );
 
    bindings[key] = fn;
    return this;
  }
 
  /**
   * Alias of attach(methodName, key, fn, true).
   */
  public static attachBefore(methodName: string, key: string, fn: Function) {
    return this.attach(methodName, key, fn, true);
  }
 
  /**
   * This methods is just an helper to deal with custom indexes. It takes as
   * arguments the name of the index and an object containing all the different
   * functions to bind to the methods.
   *
   * Here is a basic example, that creates an index to keep the number of nodes
   * in the current graph. It also adds a method to provide a getter on that
   * new index:
   *
   *  > sigma.classes.graph.addIndex('nodesCount', {
   *  >   constructor: function() {
   *  >     this.nodesCount = 0;
   *  >   },
   *  >   addNode: function() {
   *  >     this.nodesCount++;
   *  >   },
   *  >   dropNode: function() {
   *  >     this.nodesCount--;
   *  >   }
   *  > });
   *  >
   *  > sigma.classes.Graph.addMethod('getNodesCount', function() {
   *  >   return this.nodesCount;
   *  > });
   *  >
   *  > var myGraph = new sigma.classes.graph();
   *  > console.log(myGraph.getNodesCount()); // outputs 0
   *  >
   *  > myGraph.addNode({ id: '1' }).addNode({ id: '2' });
   *  > console.log(myGraph.getNodesCount()); // outputs 2
   *
   * @param  {string} name     The name of the index.
   * @param  {object} bindings The object containing the functions to bind.
   * @return {object}          The global graph constructor.
   */
  public static addIndex(name: string, bindings: NamedBindings) {
    Iif (
      typeof name !== "string" ||
      Object(bindings) !== bindings ||
      arguments.length !== 2
    )
      throw new Error("addIndex: Wrong arguments.");
 
    if (_indexes.has(name)) {
      throw new Error(`The index "${name}" already exists.`);
    }
 
    // Store the bindings:
    _indexes.add(name);
 
    // Attach the bindings:
    Object.keys(bindings).forEach(k => {
      if (typeof bindings[k] !== "function") {
        throw new Error("The bindings must be functions.");
      }
      Graph.attach(k, name, bindings[k]!);
    });
 
    return this;
  }
}
 
Graph.__addOwnMethod("addNode");
Graph.__addOwnMethod("addEdge");
Graph.__addOwnMethod("dropNode");
Graph.__addOwnMethod("dropEdge");
Graph.__addOwnMethod("kill");
Graph.__addOwnMethod("clear");
Graph.__addOwnMethod("read");
Graph.__addOwnMethod("nodes");
Graph.__addOwnMethod("degree");
Graph.__addOwnMethod("edges");
 
export default Graph;