Sha256: 3f4d23c5d36dcdec2059782c0723ffc550f599a362a4d35e6451ae0c93bd79fa

Contents?: true

Size: 910 Bytes

Versions: 211

Compression:

Stored size: 910 Bytes

Contents

const ALPHA = 'abcdefghijklmnopqrstuvwxyz';

function generateKey() {
  return Array.apply(null, Array(100))
    .map(() => ALPHA[Math.floor(Math.random() * ALPHA.length)])
    .join('');
}

function xCode(key, inText, sign) {
  return [...inText]
    .reduce((outText, letter, ii) => {
      const offset = sign * ALPHA.indexOf(key[mod(ii, key.length)]);
      outText += ALPHA[mod(ALPHA.indexOf(letter) + offset, ALPHA.length)];
      return outText;
    }, '');
}

const mod = (n, m) => (n % m + m) % m;

export default function (key) {

  if (typeof key === 'undefined') {
    key = generateKey();
  } else if (key.length === 0 || key.match(/[^a-z]/, "g")) {
    throw new Error("Bad key");
  }

  return {
    key:    key,
    encode: function (plainText) {
      return xCode(this.key, plainText, 1);
    },
    decode: function (encodedText) {
      return xCode(this.key, encodedText, -1);
    }
  }
}

Version data entries

211 entries across 211 versions & 1 rubygems

Version Path
trackler-2.2.0.0 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.55 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.54 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.53 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.52 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.51 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.50 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.49 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.48 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.47 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.46 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.45 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.44 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.43 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.42 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.41 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.40 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.39 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.38 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.1.0.37 tracks/ecmascript/exercises/simple-cipher/example.js