Skip to content

Instantly share code, notes, and snippets.

@DominoPivot
Last active August 19, 2022 16:58
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 DominoPivot/7e2e184d49426db6a88714dff63d7fda to your computer and use it in GitHub Desktop.
Save DominoPivot/7e2e184d49426db6a88714dff63d7fda to your computer and use it in GitHub Desktop.
Monoalphabetic Substitution Cipher Helper
// A tool to help you create or solve monoalphabetic substitution ciphers.
// This code is left to the public domain.
//
// Run this in a Node interactive session or web browser console.
// Start by creating a machine instance with m = machine(message);
// Call m.replace() to progressively replace each letter with a new one.
// Use lowercase for your original message and uppercase for the
// substituted letters so you and the code can tell them apart.
// m.frequency will give you the fequency of each letter in the message.
function machine (code) {
let state = code;
let previous = state;
return Object.freeze({
replace (a, b) {
previous = state;
state = state.replace(new RegExp(a, "g"), b);
return state;
},
undo () {
[state, previous] = [previous, state];
return state;
},
reset () {
[state, previous] = [code, state];
return state;
},
get frequency () {
return [...state].reduce((freq, char) => (freq[char] = freq[char] + 1 || 1, freq), {});
},
get state () {
return state;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment