exportconstcode=(s:string,num:number):string=>{constmap=(c:string)=>c.charCodeAt(0)-97constunmap=(x:number)=>String.fromCharCode(x+97)constf=(x:number)=>(num*x)%26letr=''for(leti=0;i<s.length;i++){constx=map(s[i])constch=unmap(f(x))r+=ch}returnString(num)+r}// calculate modular inverse// https://rosettacode.org/wiki/Modular_inverse#JavaScriptconstmodInverse=(a:number,b:number):number=>{a%=bfor(letx=1;x<b;x++){if((a*x)%b===1){returnx}}return1}exportconstdecode=(r:string):string=>{constmatch=r.match(/^\d+/)letnum=-1if(match){num=parseInt(match[0])r=r.substring(match[0].length)}consta_=modInverse(num,26)if(num===-1||a_===1){return'Impossible to decode'}constmap=(c:string)=>c.charCodeAt(0)-97constunmap=(x:number)=>String.fromCharCode(x+97)constf=(x:number)=>(a_*x)%26lets=''for(leti=0;i<r.length;i++){constx=map(r[i])constch=unmap(f(x))s+=ch}returns}
Test
import{code,decode}from'.'describe('encode data',()=>{it('should return encoded data',()=>{expect(code('mer',6015)).toBe('6015ekx')expect(code('hello',9317)).toBe('9317lkvvw')expect(code('goodbye',1234603)).toBe('1234603kggftoy')})})describe('decode data',()=>{it('should return decoded data',()=>{expect(decode('6015ekx')).toBe('mer')expect(decode('9317lkvvw')).toBe('hello')expect(decode('1234603kggftoy')).toBe('goodbye')})it('should return "Impossible to decode" if unable to decode',()=>{expect(decode('5057aan')).toBe('Impossible to decode')expect(decode('xxx5057aan')).toBe('Impossible to decode')})})
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
TypeScript plus tests
github.com/kiliman/dev-to-daily-ch...
Test