/**
 * Utility functions for working with Sets as Map keys
 * 
 * Provides canonical string representations for Set objects to ensure
 * consistent and efficient Map key operations.
 */

/**
 * Get a canonical string key for a Set
 * @param {Set} set - The set to create a key for
 * @returns {string} Canonical string representation
 */
export function getSetKey(set) {
  if (set.size === 0) return ''; // Consistent key for empty set
  return Array.from(set).sort().join(',');
}

/**
 * Create a Set from a canonical string key
 * @param {string} key - The canonical string key
 * @param {Array} stateSpace - The state space to validate against
 * @returns {Set} The reconstructed set
 */
export function setFromKey(key, stateSpace = null) {
  if (key === '') return new Set();
  
  const elements = key.split(',');
  const set = new Set(elements);
  
  // Validate against state space if provided
  if (stateSpace) {
    for (const element of set) {
      if (!stateSpace.includes(element)) {
        throw new Error(`Element ${element} not found in state space`);
      }
    }
  }
  
  return set;
}

/**
 * Check if two sets are equal by comparing their canonical keys
 * @param {Set} set1 - First set
 * @param {Set} set2 - Second set
 * @returns {boolean} True if sets are equal
 */
export function setsEqual(set1, set2) {
  return getSetKey(set1) === getSetKey(set2);
}
