Sha256: 201e8c344d4da628ddb73bb12bc0c8b63dc53d76b1ba671d2ab708ef770a7006

Contents?: true

Size: 872 Bytes

Versions: 185

Compression:

Stored size: 872 Bytes

Contents

const ALPHA = 'abcdefghijklmnopqrstuvwxyz';

function generateKey() {
  return Array(...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,
    encode(plainText) {
      return xCode(this.key, plainText, 1);
    },
    decode(encodedText) {
      return xCode(this.key, encodedText, -1);
    },
  };
}

Version data entries

185 entries across 185 versions & 1 rubygems

Version Path
trackler-2.2.1.159 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.158 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.157 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.156 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.155 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.154 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.153 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.152 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.151 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.150 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.149 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.148 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.147 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.146 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.145 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.144 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.143 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.142 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.141 tracks/ecmascript/exercises/simple-cipher/example.js
trackler-2.2.1.140 tracks/ecmascript/exercises/simple-cipher/example.js