All files / src miscellaneous.js

0% Statements 0/18
0% Branches 0/6
0% Functions 0/2
0% Lines 0/16

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                                                                                           
export function groupIntoConsecutiveBuckets(arr, periodicity) {
  if (arr.length == 0) {
    return []
  }
  // Sort the array
  arr.sort((a, b) => a - b)
 
  // Initialize an array to store buckets
  const buckets = []
 
  // Initialize the first bucket with the first element of the array
  let currentBucket = [arr[0]]
 
  // Iterate through the sorted array
  for (let i = 1; i < arr.length; i++) {
    // Calculate the gap considering the periodicity
    let gap = (arr[i] - arr[i - 1] + periodicity) % periodicity
 
    // If the current element is consecutive to the previous one, add it to the current bucket
    if (gap === 1) {
      currentBucket.push(arr[i])
    } else {
      // If there's a gap, start a new bucket
      buckets.push(currentBucket)
      currentBucket = [arr[i]]
    }
  }
 
  // Push the last bucket into the buckets array
  buckets.push(currentBucket)
 
  // Check if the last bucket and the first bucket are consecutive
  if (
    (buckets[buckets.length - 1][buckets[buckets.length - 1].length - 1] + 1) %
      periodicity ===
    buckets[0][0]
  ) {
    // Merge the last bucket with the first one
    buckets[0] = buckets[buckets.length - 1].concat(buckets[0])
    // Remove the last bucket
    buckets.pop()
  }
 
  return buckets
}