# all files / Github/diagram-js/lib/util/ Collections.js

91.3% Statements 21/23
91.67% Branches 22/24
100% Functions 3/3
91.3% Lines 21/23

    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

    5675×
    387×

    5288×

    5288×
    5183×

    5288×

    20133×

    20133×
    14603×

    20133×

    20133×

    357×

    26×

    331×

    102×

    229×

    19878×

    4400×

    15478×

    655×

    655×

     /**
     * Failsafe remove an element from a collection
     *
     * @param  {Array<Object>} [collection]
     * @param  {Object} [element]
     *
     * @return {Number} the previous index of the element
     */
    export function remove(collection, element) {

      if (!collection || !element) {
        return -1;
      }

      var idx = collection.indexOf(element);

      if (idx !== -1) {
        collection.splice(idx, 1);
      }

      return idx;
    }

    /**
     * Fail save add an element to the given connection, ensuring
     * it does not yet exist.
     *
     * @param {Array<Object>} collection
     * @param {Object} element
     * @param {Number} idx
     */
    export function add(collection, element, idx) {

      Iif (!collection || !element) {
        return;
      }

      if (typeof idx !== 'number') {
        idx = -1;
      }

      var currentIdx = collection.indexOf(element);

      if (currentIdx !== -1) {

        if (currentIdx === idx) {
          // nothing to do, position has not changed
          return;
        } else {

          if (idx !== -1) {
            // remove from current position
            collection.splice(currentIdx, 1);
          } else {
            // already exists in collection
            return;
          }
        }
      }

      if (idx !== -1) {
        // insert at specified position
        collection.splice(idx, 0, element);
      } else {
        // push to end
        collection.push(element);
      }
    }

    /**
     * Fail save get the index of an element in a collection.
     *
     * @param {Array<Object>} collection
     * @param {Object} element
     *
     * @return {Number} the index or -1 if collection or element do
     *                  not exist or the element is not contained.
     */
    export function indexOf(collection, element) {

      Iif (!collection || !element) {
        return -1;
      }

      return collection.indexOf(element);
    }