All files / app/assets/javascripts/lib/utils array_utility.js

100% Statements 16/16
80% Branches 8/10
100% Functions 5/5
100% Lines 14/14

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                21x 16x   16x 8x     8x 8x 8x 8x                 39x 126x                     21x 16x 6x   11x    
/**
 * Return a shallow copy of an array with two items swapped.
 *
 * @param {Array} array - The source array
 * @param {Number} leftIndex - Index of the first item
 * @param {Number} rightIndex - Index of the second item
 * @returns {Array} new array with the left and right items swapped
 */
export const swapArrayItems = (array, leftIndex = 0, rightIndex = 0) => {
  const copy = array.slice();
 
  if (leftIndex >= array.length || leftIndex < 0 || rightIndex >= array.length || rightIndex < 0) {
    return copy;
  }
 
  const temp = copy[leftIndex];
  copy[leftIndex] = copy[rightIndex];
  copy[rightIndex] = temp;
  return copy;
};
 
/**
 * Return an array with all duplicate items from the given array
 *
 * @param {Array} array - The source array
 * @returns {Array} new array with all duplicate items
 */
export const getDuplicateItemsFromArray = (array) => [
  ...new Set(array.filter((value, index) => array.indexOf(value) !== index)),
];
 
/**
 * Toggles the presence of an item in a given array.
 * Use pass by reference when toggling non-primivive types.
 *
 * @param {Array} array - The array to use
 * @param {Any} item - The array item to toggle
 * @returns {Array} new array with toggled item
 */
export const toggleArrayItem = (array, value) => {
  if (array.includes(value)) {
    return array.filter((item) => item !== value);
  }
  return [...array, value];
};