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

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 TypeScript, array destructuring swapping:
 * `[textArr[left], textArr[right]] = [textArr[right], textArr[left]]`
 * is strongly preferred for readability and optimizer friendliness.
 *
 * @param textArr - Mutable array of single-character strings.
 * @param left - Zero-based index of the first character.
 * @param right - Zero-based index of the second character.
 */
function xorSwapCharacters(textArr: string[], left: number, right: number): void {
  // Guard clause: check bounds and handle empty array
  if (
    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, apply bitwise XOR, and convert back to string
  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(): void {
  const original: string = "hello";
  const textArr: string[] = Array.from(original);

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

  xorSwapCharacters(textArr, 1, 4);

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

main();



/*
run:

Before: hello
After:  holle

*/

 



answered Sep 30 by avibootz
...