Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .oss-upstream
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TheAlgorithms/TypeScript
13 changes: 13 additions & 0 deletions ciphers/test/xor_cipher.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
})
})
4 changes: 2 additions & 2 deletions ciphers/xor_cipher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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('')