Path: blob/master/lib/rammerhead/src/util/StrShuffler.js
6530 views
/*12baseDictionary originally generated with (certain characters was removed to avoid breaking pages):34let str = '';5for (let i = 32; i <= 126; i++) {6let c = String.fromCharCode(i);7if (c !== '/' && c !== '_' && encodeURI(c).length === 1) str += c;8}910*/1112const mod = (n, m) => ((n % m) + m) % m;13const baseDictionary = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz~-';14const shuffledIndicator = '_rhs';15const generateDictionary = function () {16let str = '';17const split = baseDictionary.split('');18while (split.length > 0) {19str += split.splice(Math.floor(Math.random() * split.length), 1)[0];20}21return str;22};23class StrShuffler {24constructor(dictionary = generateDictionary()) {25this.dictionary = dictionary;26}27shuffle(str) {28if (str.startsWith(shuffledIndicator)) {29return str;30}31let shuffledStr = '';32for (let i = 0; i < str.length; i++) {33const char = str.charAt(i);34const idx = baseDictionary.indexOf(char);35if (char === '%' && str.length - i >= 3) {36shuffledStr += char;37shuffledStr += str.charAt(++i);38shuffledStr += str.charAt(++i);39} else if (idx === -1) {40shuffledStr += char;41} else {42shuffledStr += this.dictionary.charAt(mod(idx + i, baseDictionary.length));43}44}45return shuffledIndicator + shuffledStr;46}47unshuffle(str) {48if (!str.startsWith(shuffledIndicator)) {49return str;50}5152str = str.slice(shuffledIndicator.length);5354let unshuffledStr = '';55for (let i = 0; i < str.length; i++) {56const char = str.charAt(i);57const idx = this.dictionary.indexOf(char);58if (char === '%' && str.length - i >= 3) {59unshuffledStr += char;60unshuffledStr += str.charAt(++i);61unshuffledStr += str.charAt(++i);62} else if (idx === -1) {63unshuffledStr += char;64} else {65unshuffledStr += baseDictionary.charAt(mod(idx - i, baseDictionary.length));66}67}68return unshuffledStr;69}70}7172StrShuffler.baseDictionary = baseDictionary;73StrShuffler.shuffledIndicator = shuffledIndicator;74StrShuffler.generateDictionary = generateDictionary;7576module.exports = StrShuffler;777879