Sha256: a2234022369cbcc446f0fc8e8b300cdc815e7e5e286365d8d7275f6088f24d0a

Contents?: true

Size: 1.24 KB

Versions: 51

Compression:

Stored size: 1.24 KB

Contents

'use strict';

var ALPHABET = 'abcdefghijklmnopqrstuvwxyz';

function randomKey() {
  var result;
  for ( var i = 0; i < 100; i++ ) {
    result += ALPHABET[randomUpTo(ALPHABET.length)];
  }
  return result;
}

function randomUpTo(n) {
  return Math.floor(Math.random() * n);
}

module.exports = function (userDefinedKey) {
  var key;

  function addEncodedCharacter(character, index) {
    var i = ALPHABET.indexOf(character) + ALPHABET.indexOf(key[index % key.length]);
    if (i >= ALPHABET.length) { i -= ALPHABET.length; }
    this.push(ALPHABET[i]);
  }

  function addDecodedCharacter(character, index) {
    var i = ALPHABET.indexOf(character) - ALPHABET.indexOf(key[index % key.length]);
    if (i < 0) { i += ALPHABET.length; }
    this.push(ALPHABET[i]);
  }

  this.encode = function (plaintext) {
    var characters = [];
    plaintext.split('').forEach( addEncodedCharacter, characters );
    return characters.join('');
  };

  this.decode = function (ciphertext) {
    var characters = [];
    ciphertext.split('').forEach( addDecodedCharacter, characters );
    return characters.join('');
  };

  this.key = userDefinedKey || randomKey();
  key = this.key;

  if (userDefinedKey === '' || key.match(/[\dA-Z]/)) {
    throw new Error('Bad key');
  }
};

Version data entries

51 entries across 51 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.179 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.178 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.177 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.176 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.175 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.174 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.173 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.172 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.171 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.170 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.169 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.167 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.166 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.165 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.164 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.163 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.162 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.161 tracks/javascript/exercises/simple-cipher/example.js
trackler-2.2.1.160 tracks/javascript/exercises/simple-cipher/example.js