diff --git a/.oss-upstream b/.oss-upstream new file mode 100644 index 00000000..4e304ffa --- /dev/null +++ b/.oss-upstream @@ -0,0 +1 @@ +TheAlgorithms/TypeScript diff --git a/ciphers/test/xor_cipher.test.ts b/ciphers/test/xor_cipher.test.ts index 0607d6a3..38db6c14 100644 --- a/ciphers/test/xor_cipher.test.ts +++ b/ciphers/test/xor_cipher.test.ts @@ -5,4 +5,17 @@ describe('Testing XORCipher function', () => { expect(XORCipher('test', 32)).toBe('TEST') expect(XORCipher('TEST', 32)).toBe('test') }) + + it('encrypts newline and other line-terminator characters', () => { + // /./g without the s-flag skips \n, \r — Array.from handles them correctly + expect(XORCipher('\n', 1)).toBe(String.fromCharCode(10 ^ 1)) + expect(XORCipher('\r', 1)).toBe(String.fromCharCode(13 ^ 1)) + expect(XORCipher('A\nB', 1)).toBe( + String.fromCharCode(65 ^ 1) + String.fromCharCode(10 ^ 1) + String.fromCharCode(66 ^ 1) + ) + }) + + it('XORCipher is its own inverse', () => { + expect(XORCipher(XORCipher('Hello\nWorld', 42), 42)).toBe('Hello\nWorld') + }) }) diff --git a/ciphers/xor_cipher.ts b/ciphers/xor_cipher.ts index 72d91e68..d6930191 100644 --- a/ciphers/xor_cipher.ts +++ b/ciphers/xor_cipher.ts @@ -10,6 +10,6 @@ * @return {string} encrypted string */ export const XORCipher = (str: string, key: number): string => - str.replace(/./g, (char: string) => + Array.from(str, (char: string) => String.fromCharCode(char.charCodeAt(0) ^ key) - ) + ).join('')