Skip to content

Instantly share code, notes, and snippets.

@jcorbin
Created November 10, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcorbin/227b490311fea60c4a4cd620274ded19 to your computer and use it in GitHub Desktop.
Save jcorbin/227b490311fea60c4a4cd620274ded19 to your computer and use it in GitHub Desktop.
simple markov-powered text corruptor
// @ts-check
/**
* Markov transition table on characters.
* Empty means "transparent", i.e let the underlying string through
*
* @typedef {Object<string, number>} Weights
* @typedef {Object<string, Weights>} Transitions
*/
/**
* Steps through a transition table.
*
* @param {Transitions} table
* @param {string} c
*/
function next(table, c) {
const poss = table[c];
if (!poss) return '';
let choice='', best=NaN;
for (const [char, weight] of Object.entries(poss)) {
const score = Math.pow(Math.random(), 1/weight);
if (isNaN(best) || score > best)
choice=char, best=score;
}
return choice;
}
const succ = {
'': {'!': 1, '@': 1, '?': 1, '.': 1},
'!': {'@': 5, '': 3},
'@': {'?': 5, '': 3},
'?': {'!': 5, '': 3},
'.': {'.': 5, '': 3},
};
/** @param {string} s */
function corrupt(s) {
let state = next(succ, '');
let r = '';
for (let i=0; i<s.length; i++) {
state = next(succ, state);
r += state ? state : s[i];
}
return r;
}
console.log(corrupt('hello'));
console.log(corrupt('world'));
console.log(corrupt('secret'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment