all files / 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                    5557× 382×     5175×   5175× 5092×     5175×                         20980×       20980× 15414×     20980×   20980×   408×   26×     382×   137×     245×         20709×   4478×     16231×                               633×       633×    
/**
 * 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);
}