Untitled

mail@pastecode.io avatar
unknown
javascript
3 years ago
927 B
3
Indexable
function VigenèreCipher(key, abc) {
  let keyArr = key.split('');
  const alpha = abc.split('');
  let keyLength = keyArr.length;
  for (let i=0;keyArr.length<alpha.length; i++) {
    if (!keyArr[i]) {keyArr[i]=keyArr[i%keyLength]};
  }
  this.encode = function (str) {
      let resultArr = [];    
      let shift = 0;                         
   str.split('').map ((c,i)=>{
     resultArr[i] = this.shift(c,alpha.indexOf(keyArr[i]))
   });
    return resultArr.join('');
  };
  this.decode = function (str) {
    let resultArr = [];
    let shift = 0;
    str.split('').map((c,i)=> {
      resultArr[i] = this.shift(c,alpha.length-alpha.indexOf(keyArr[i]));
    })
    return resultArr.join('');   
  }
  this.shift = function (el,shift){
    if (alpha.includes(el)){
     return (shift+alpha.indexOf(el)>alpha.length-1)?alpha[(shift+alpha.indexOf(el)-alpha.length)]:alpha[shift+alpha.indexOf(el)]
  } else return el;
  }
}