Skip to content

Instantly share code, notes, and snippets.

@mrclay
Created August 26, 2024 15:37
Show Gist options
  • Save mrclay/7a6bc16fd8ac050c66f33fb236842137 to your computer and use it in GitHub Desktop.
Save mrclay/7a6bc16fd8ac050c66f33fb236842137 to your computer and use it in GitHub Desktop.
TypeScript version of rotUrl
// From https://github.com/locutusjs/locutus/blob/main/src/php/strings/strtr.js
// but adapted to the all-strings case.
function strtr(str: string, trFrom: string, trTo: string) {
let j = 0;
let lenStr = 0;
let lenFrom = 0;
let istr = '';
let ret = '';
let match = false;
// Walk through subject and replace chars when needed
lenStr = str.length;
lenFrom = trFrom.length;
for (let i = 0; i < lenStr; i += 1) {
match = false;
istr = str.charAt(i);
for (j = 0; j < lenFrom; j += 1) {
if (istr === trFrom.charAt(j)) {
match = true;
break;
}
}
if (match) {
ret += trTo.charAt(j);
} else {
ret += str.charAt(i);
}
}
return ret;
}
/**
* Rot35 for URLs. To avoid increasing size during urlencode(), commonly encoded
* chars are mapped to more rarely used chars (end of the uppercase alpha).
* PHP version: https://gist.github.com/mrclay/1225832
*/
export default function rotUrl(url: string) {
return strtr(
url,
'./-:?=&%# ZQXJKVWPY abcdefghijklmnopqrstuvwxyz123456789ABCDEFGHILMNORSTU',
'ZQXJKVWPY ./-:?=&%# 123456789ABCDEFGHILMNORSTUabcdefghijklmnopqrstuvwxyz',
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment