How to use XOR to swap two characters in a string in JavaScript

1 Answer

0 votes
/**
 * Swaps two characters in an array of characters using the XOR swap algorithm.
 *
 * This function demonstrates bitwise XOR swapping for educational purposes.
 * In production JavaScript, array destructuring swapping:
 * `[arr[left], arr[right]] = [arr[right], arr[left]]`
 * is strongly preferred for readability and optimizer friendliness.
 *
 * @param {string[]} textArr - Mutable array of single-character strings.
 * @param {number} left - Zero-based index of the first character.
 * @param {number} right - Zero-based index of the second character.
 * @returns {void}
 */
function xorSwapCharacters(textArr, left, right) {
  // Guard clause: check for invalid inputs, empty array, or out-of-bounds indices
  if (
    !Array.isArray(textArr) ||
    textArr.length === 0 ||
    left < 0 ||
    left >= textArr.length ||
    right < 0 ||
    right >= textArr.length
  ) {
    return;
  }

  // XOR swap fails if left === right because (x ^ x) evaluates to 0
  if (left === right) {
    return;
  }

  // Convert UTF-16 code units, perform bitwise XOR, and convert back to characters
  textArr[left] = String.fromCharCode(
    textArr[left].charCodeAt(0) ^ textArr[right].charCodeAt(0)
  );
  textArr[right] = String.fromCharCode(
    textArr[right].charCodeAt(0) ^ textArr[left].charCodeAt(0)
  );
  textArr[left] = String.fromCharCode(
    textArr[left].charCodeAt(0) ^ textArr[right].charCodeAt(0)
  );
}

function main() {
  const original = "hello";
  const textArr = Array.from(original);

  console.log(`Before: ${textArr.join("")}`);

  xorSwapCharacters(textArr, 1, 4);

  const result = textArr.join("");
  console.log(`After:  ${result}`);
}

main();



/*
run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...