Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:40
Show Gist options
  • Save rfprod/450a388358fdc4be8618a306aa07f327 to your computer and use it in GitHub Desktop.
Save rfprod/450a388358fdc4be8618a306aa07f327 to your computer and use it in GitHub Desktop.
KamaSutra Cipher
function KamaSutraCipher(key) {
this.pairs = key;
this.encode = function (str) {
let encoded = '';
for (let k in str) {
loop:
for (let i = 0, max = this.pairs.length; i < max; i++) {
const indexInPair = this.pairs[i].indexOf(str[k]);
if (indexInPair !== -1) {
encoded += (indexInPair === 0) ? this.pairs[i][1] : this.pairs[i][0];
break loop;
}
if (i === max - 1) { encoded += str[k]; } // if char is not present in pairs
}
}
return encoded;
};
this.decode = function (str) {
return this.encode(str);
}
}
// TEST
const key = [
['d', 'p'],
['n', 'o'],
['a', 'w'],
['f', 'c'],
['h', 's'],
['l', 'v'],
['m', 'j'],
['x', 'b'],
['e', 'z'],
['r', 'i'],
['k', 'y'],
['u', 'q'],
['t', 'g']
];
let coder = new KamaSutraCipher(key);
c.encode('mutt'); // 'jqgg'
c.decode('jqgg'); // 'mutt'
c.encode('panda'); // 'dwopw'
c.decode('dwopw'); // 'panda'
c.encode('panCda'); // 'dwoCpw'
c.decode('dwoCpw'); // 'panCda'

KamaSutra Cipher

Function KamaSutraCipher encodes / decodes input string based on previously provided key pairs dictionary.

It replaces a character in string if it is present in key array and leaves it as is if it is not.

Example key pairs dictionary: [ ['d', 'p'], ['n', 'o'], ['a', 'w'], ['f', 'c'], ['h', 's'], ['l', 'v'], ['m', 'j'], ['x', 'b'], ['e', 'z'], ['r', 'i'], ['k', 'y'], ['u', 'q'], ['t', 'g'] ]

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment